Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to change dictionary key

Tags:

c#

dictionary

I am wondering is there a better way to change a dictionary key, for example:

var dic = new Dictionary<string, int>(); dic.Add("a", 1); 

and later on I decided to make key value pair to be ("b" , 1) , is it possible to just rename the key rather than add a new key value pair of ("b",1) and then remove "a" ?

Thanks in advance.

like image 701
Yuan Avatar asked Jun 27 '11 21:06

Yuan


People also ask

How do I change the 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 we change key in dictionary c#?

The Dictionary in c# is implemented as a hashtable. Therefore, if you were able to change the key via some Dictionary. ChangeKey method, the entry would have to be re-hashed. So it's not really any different (aside from convenience) than removing the entry, and then adding it again with the new key.


1 Answers

No, you cannot rename keys once that have been added to a Dictionary. If you want a rename facility, perhaps add your own extension method:

public static void RenameKey<TKey, TValue>(this IDictionary<TKey, TValue> dic,                                       TKey fromKey, TKey toKey) {   TValue value = dic[fromKey];   dic.Remove(fromKey);   dic[toKey] = value; } 
like image 183
ColinE Avatar answered Oct 05 '22 15:10

ColinE