轉載自:https://codedefault.com/s/how-to-update-the-value-stored-in-dictionary-in-csharp-application
問題描述
在.NET/C#程序開發中,我們如何修改字典(Dictionary
)中指定鍵對應的值呢Dictionary<string,int>
?
方案一
直接根據指定的鍵修改,如:
myDictionary[myKey] = myNewValue;
方案二
根據鍵的索引訪問指定鍵的位置,然後修改:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]);//輸出結果爲:2
方案三
我們也可以使用字典(Dictionary
)的TryGetValue()
方法來判斷指定鍵是否存在,如:
void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
int val;
if (dic.TryGetValue(key, out val))
{
//如果指定的字典的鍵存在
dic[key] = val + newValue;
}
else
{
//不存在,則添加
dic.Add(key, newValue);
}
}
方案四
我們還可以使用LINQ
來訪問字典的鍵並修改對應的值,如:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);