How to modify key in a dictionary in C#

Bernard Larouche picture Bernard Larouche · Dec 21, 2009 · Viewed 82.3k times · Source

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

I have the following dictionary :

SortedDictionary<int,SortedDictionary<string,List<string>>>

I want to loop through this sorted dictionary and change the key to key+1 if the key value is greater than a certain amount.

Answer

Dan Tao picture Dan Tao · Dec 21, 2009

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);
}