Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify key in a dictionary in C#

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.

like image 597
Bernard Larouche Avatar asked Dec 21 '09 02:12

Bernard Larouche


People also ask

How do you modify a dictionary key?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

Can you update a key in a dictionary in c#?

As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value.

How do you add a key to a dictionary?

You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.

How do you check if a key is in a dictionary c#?

Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.


2 Answers

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); } 
like image 124
Dan Tao Avatar answered Sep 25 '22 06:09

Dan Tao


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

like image 41
jason Avatar answered Sep 24 '22 06:09

jason