目前,我有比這一個(間接更新)沒有其他辦法:有什麼方法可以直接在.NET中更新字典的Key元素?
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);
}
}
你有別的更好的辦法?
當然,上面的方法只是一個簡單的方法,爲了使其工作得很好而不會引發任何異常,我們必須檢查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;
}
}
非常感謝您提前!
刪除和重新添加是唯一的方法。密鑰用作值的標識,因此密鑰更改的邏輯上不可能;這意味着關鍵是指一個不同的實體。 '字典'堅持這個觀點。 – 2013-04-27 18:10:49
如果你必須做很多事情,最好使用另一種數據結構。 – 2013-04-27 18:11:56
你爲什麼需要這個? – 2013-04-27 18:14:46