Best way to change dictionary key

public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> 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<TKey, TValue>(this IDictionary<TKey, TValue> 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;
}

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;
}

Do you like this simple code?

var newDictionary= oldDictionary.ReplaceInKeys<object>("_","-");

It replace '_' with '-' in all keys


If

  • type of your key is string

and

  • you want replace a string with other string in all keys of the dictionary

then use my way


You just need to add the following class to your app:

public static class DicExtensions{

    public static void ReplaceInKeys<TValue>(this IDictionary<string, TValue> oldDictionary, string replaceIt, string withIt)
    {
          // Do all the works with just one line of code:
          return oldDictionary
                 .Select(x=> new KeyValuePair<string, TValue>(x.Key.Replace(replaceIt, withIt), x.Value))
                 .ToDictionary(x=> x.Key,x=> x.Value);
    }
}

I use Linq to change my dictionary keys (regenerate a dictionary by linq)

The magic step is ToDictionary() method.


Note: We can make an advanced Select include a block of codes for complicated cases instead of a simple lambda.

Select(item =>{
            .....Write your Logic Codes Here....

            return resultKeyValuePair;
       })

Tags:

C#

Dictionary