Best way to change dictionary key

后端 未结 4 1347
忘掉有多难
忘掉有多难 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:19

    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(this IDictionary dic,
                                          TKey fromKey, TKey toKey)
    {
      TValue value = dic[fromKey];
      dic.Remove(fromKey);
      dic[toKey] = value;
    }
    

提交回复
热议问题