views:

658

answers:

2

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...

Thanks

+13  A: 

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).

Jason
+2  A: 

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
List<int> keysToUpdate = new List<int>();

foreach (KeyValuePair<int, SortedDictionary<string, List<string>>> 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);
}
Dan Tao
I think you might encounter an OutOfBoundsException with keyToUpdate +1
0A0D
Why would that happen?
Anon.
Thank you very much DanThis is exactly what I was looking for..
Bernard Larouche
@Roboto: You might get an `OverflowException` if `keyToUpdate == int.MaxValue`; other than that, though, I don't see how adding two integers is going to give an `OutOfBoundsException`...
Dan Tao
@Roboto: Maybe you meant on adding the new key to the dictionary? In that case, no, the `SortedDictionary<TKey, TValue>.Add` method doesn't throw an `OutOfBoundsException`, only `ArgumentNullException` and `ArgumentException`; see http://msdn.microsoft.com/en-us/library/7620520y.aspx.
Dan Tao