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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With