Best way to change dictionary key

后端 未结 4 1352
忘掉有多难
忘掉有多难 2020-12-03 10:02

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

var dic = new Dictionary();
dic.Add(\"a\", 1);
4条回答
  •  执念已碎
    2020-12-03 10:40

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

提交回复
热议问题