本文介绍了改变字典的键的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有更好的方法来改变一个字典的键,例如:
I am wondering is there a better way to change a dictionary key, for example:
var dic = new Dictionary<string, int>();
dic.Add("a", 1);
和后来我决定把键值对是(B,1),是它可能只是重命名键,而不是添加一个新的键值对(b,1),然后取出事先一?
and later on I decided to make key value pair to be ("b" , 1) , is it possible to just rename the key rather than add a new key value pair of ("b",1) and then remove "a" ?
谢谢。
推荐答案
没有,你不能重命名一次按键已添加到字典。如果你想有一个重命名工具,也许添加自己的扩展方法:
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;
}
这篇关于改变字典的键的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!