【发布时间】:2011-09-23 20:50:11
【问题描述】:
我想知道是否有更好的方法来更改字典键,例如:
var dic = new Dictionary<string, int>();
dic.Add("a", 1);
后来我决定将键值对设为 ("b" , 1) ,是否可以只重命名键而不是添加一个新的键值对 ("b",1) 然后删除“一个”?
提前致谢。
【问题讨论】:
标签: c# dictionary
我想知道是否有更好的方法来更改字典键,例如:
var dic = new Dictionary<string, int>();
dic.Add("a", 1);
后来我决定将键值对设为 ("b" , 1) ,是否可以只重命名键而不是添加一个新的键值对 ("b",1) 然后删除“一个”?
提前致谢。
【问题讨论】:
标签: c# dictionary
不,一旦添加到字典中,您就不能重命名键。如果你想要一个重命名工具,也许添加你自己的扩展方法:
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;
}
【讨论】:
ChangeKey 或UpdateKey :)
c# 中的Dictionary 实现为哈希表。因此,如果您能够通过某种Dictionary.ChangeKey 方法更改密钥,则必须重新散列该条目。因此,它与删除条目然后使用新密钥再次添加它并没有什么不同(除了方便之外)。
【讨论】:
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;
}
与 Colin 的回答相同,但不抛出异常,而是在失败时返回 false。事实上,考虑到编辑键值是危险的,我认为这种方法应该是字典类中的默认方法,因此类本身应该给我们一个安全的选项。
从 .NET Core 开始,这样效率更高:
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;
}
【讨论】:
你喜欢这个简单的代码吗?
var newDictionary= oldDictionary.ReplaceInKeys<object>("_","-");
它将所有键中的
'_'替换为'-'
如果
key 的类型是string 和
那么用我的方式
您只需将以下类添加到您的应用中:
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);
}
}
我使用 Linq 来更改我的字典键(通过
linq重新生成字典)神奇的步骤是
ToDictionary()方法。
注意:我们可以让一个高级的Select包含一个用于复杂情况的代码块,而不是一个简单的 lambda。
Select(item =>{
.....Write your Logic Codes Here....
return resultKeyValuePair;
})
【讨论】: