How to modify key in a dictionary in C#

后端 未结 4 1182
刺人心
刺人心 2020-12-01 07:30

How can I change the value of a number of keys in a dictionary.

I have the following dictionary :

SortedDictionary

        
相关标签:
4条回答
  • 2020-12-01 07:38

    As Jason said, you can't change the key of an existing dictionary entry. You'll have to remove/add using a new key like so:

    // we need to cache the keys to update since we can't
    // modify the collection during enumeration
    var keysToUpdate = new List<int>();
    
    foreach (var entry in dict)
    {
        if (entry.Key < MinKeyValue)
        {
            keysToUpdate.Add(entry.Key);
        }
    }
    
    foreach (int keyToUpdate in keysToUpdate)
    {
        SortedDictionary<string, List<string>> value = dict[keyToUpdate];
    
        int newKey = keyToUpdate + 1;
    
        // increment the key until arriving at one that doesn't already exist
        while (dict.ContainsKey(newKey))
        {
            newKey++;
        }
    
        dict.Remove(keyToUpdate);
        dict.Add(newKey, value);
    }
    
    0 讨论(0)
  • 2020-12-01 07:45

    If you don't mind recreating the dictionary, you could use a LINQ statment.

    var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>();
    var insertAt = 10;
    var newValues = dictionary.ToDictionary(
        x => x.Key < insertAt ? x.Key : x.Key + 1,
        x => x.Value);
    return new SortedDictionary<int, SortedDictionary<string, List<string>>>(newValues); 
    

    or

    var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>();
    var insertAt = 10;
    var newValues = dictionary.ToDictionary(
        x => x.Key < insertAt ? x.Key : x.Key + 1,
        x => x.Value);
    dictionary.Clear();
    foreach(var item in newValues) dictionary.Add(item.Key, item.Value);
    
    0 讨论(0)
  • 2020-12-01 07:49

    You can use LINQ statment for it

    var maxValue = 10
    sd= sd.ToDictionary(d => d.key > maxValue ? d.key : d.Key +1, d=> d.Value);
    
    0 讨论(0)
  • 2020-12-01 08:01

    You need to remove the items and re-add them with their new key. Per MSDN:

    Keys must be immutable as long as they are used as keys in the SortedDictionary(TKey, TValue).

    0 讨论(0)
提交回复
热议问题