I am wondering is there a better way to change a dictionary key, for example:
var dic = new Dictionary();
dic.Add(\"a\", 1);
public static bool ChangeKey(this IDictionary dict,
TKey oldKey, TKey newKey)
{
TValue value;
if (!dict.TryGetValue(oldKey, out value))
return false;
dict.Remove(oldKey);
dict[newKey] = value; // or dict.Add(newKey, value) depending on ur comfort
return true;
}
Same as Colin's answer, but doesn't throw exception, instead returns false on failure. In fact I'm of the opinion that such a method should be default in dictionary class considering that editing the key value is dangerous, so the class itself should give us an option to be safe.
Starting with .NET Core, this is more efficient:
public static bool ChangeKey(this IDictionary dict,
TKey oldKey, TKey newKey)
{
TValue value;
if (!dict.Remove(oldKey, out value))
return false;
dict[newKey] = value; // or dict.Add(newKey, value) depending on ur comfort
return true;
}