At the moment, I have no other way than this one (an indirect update):
private void UpdateKey(Dictionary<string,object> dict, string oldKey, string newKey){
if(dict.ContainsKey(oldKey)){
object value = dict[oldKey];
dict.Remove(oldKey);
dict.Add(newKey,value);
}
}
Do you have another better way?
Of course the above method is just a simple one, to make it work well without throwing any exception, we have to check the newKey for duplication with already keys in the Dictionary. Like this:
private void UpdateKey(Dictionary<string,object> dict, string oldKey, string newKey){
if(dict.ContainsKey(oldKey)){
object value = dict[oldKey];
dict.Remove(oldKey);
dict[newKey] = value;
}
}
Thank you very much in advance!
I would use TryGetValue
method instead of Contains
:
private void UpdateKey(Dictionary<string,object> dict, string oldKey, string newKey){
object value;
if(dict.TryGetValue(oldKey, out value)){
dict.Remove(oldKey);
dict.Add(newKey, value);
}
}
But you still need to get value first, add it with another key and remove the old one. You can't do it any other way.
By the way: you can make the method generic to operate on more then just one dictionary type:
private static void UpdateKey<TKye, TValue>(Dictionary<TKey, TValue> dict, TKey oldKey, TKey newKey){
TValue value;
if(dict.TryGetValue(oldKey, out value)){
dict.Remove(oldKey);
dict.Add(newKey, value);
}
}
Or you can event write your own Extension method on IDictionary<TKey, TValue>
:
public static class DictionaryExtensions
{
public static void UpdateKey<TKye, TValue>(this IDictionary<TKey, TValue> dict, TKey oldKey, TKey newKey){
TValue value;
if(dict.TryGetValue(oldKey, out value)){
dict.Remove(oldKey);
dict.Add(newKey, value);
}
}
}
and then call it like standard Dictionary
method:
myDict.UpdateKey(oldKey, newKey);
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