Kin*_*ing 4 .net c# dictionary key-value
目前,我没有别的办法(间接更新):
private void UpdateKey(Dictionary<string,object> dict, string oldKey, string newKey){
if(dict.ContainsKey(oldKey)){
object value = dict[oldKey];
dict.Remove(oldKey);
dict.Add(newKey,value);
}
}
Run Code Online (Sandbox Code Playgroud)
你有另一种更好的方法吗?
当然上面的方法只是一个简单的方法,为了使它运行良好而不抛出任何异常,我们必须检查newKey是否与Dictionary中的已经键重复.像这样:
private void UpdateKey(Dictionary<string,object> dict, string oldKey, string newKey){
if(dict.ContainsKey(oldKey)){
object value = dict[oldKey];
dict.Remove(oldKey);
dict[newKey] = value;
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢你提前!
Mar*_*zek 10
我会使用TryGetValue方法而不是Contains:
private void UpdateKey(Dictionary<string,object> dict, string oldKey, string newKey){
object value;
if(dict.TryGetValue(oldKey, out value)){
dict.Remove(oldKey);
dict.Add(newKey, value);
}
}
Run Code Online (Sandbox Code Playgroud)
但是你仍然需要先获得价值,用另一个键添加它并删除旧的.你不能以任何其他方式做到这一点.
顺便说一句:你可以使方法通用,只需要一个字典类型即可运行:
private static void UpdateKey<TKye, TValue>(Dictionary<TKey, TValue> dict, TKey oldKey, TKey newKey){
TValue value;
if(dict.TryGetValue(oldKey, out value)){
dict.Remove(oldKey);
dict.Add(newKey, value);
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以在以下事件上编写自己的Extension方法IDictionary<TKey, TValue>:
public static class DictionaryExtensions
{
public static void UpdateKey<TKye, TValue>(this IDictionary<TKey, TValue> dict, TKey oldKey, TKey newKey){
TValue value;
if(dict.TryGetValue(oldKey, out value)){
dict.Remove(oldKey);
dict.Add(newKey, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后像标准Dictionary方法一样调用它:
myDict.UpdateKey(oldKey, newKey);
Run Code Online (Sandbox Code Playgroud)