2012-04-12 112 views
17

我在c#中有以下代碼,基本上它是一個包含一些鍵和值的簡單字典。如何更新c#中的字典中的鍵的值?

Dictionary<string, int> dictionary = 
    new Dictionary<string, int>(); 
dictionary.Add("cat", 2); 
dictionary.Add("dog", 1); 
dictionary.Add("llama", 0); 
dictionary.Add("iguana", -1); 

我想更新密鑰 '貓' 的新價值。
我該怎麼做?

+0

真的嗎?您是否首先嚐試使用Google/Bing /首選搜索引擎? – sovanesyan 2012-04-12 12:09:32

+1

我做了,這是第一個結果!建設性的方式! – 2014-08-15 15:26:46

回答

30

你有沒有嘗試過

dictionary["cat"] = 5; 

:)

更新

dictionary["cat"] = 5+2; 
dictionary["cat"] = dictionary["cat"]+2; 
dictionary["cat"] += 2; 

當心不存在的鍵 :)

+0

wowwwww !!!!!!有用 。謝謝@JOHN – 2012-04-12 11:57:16

+0

但是如果我想爲現有值添加新值,該怎麼辦? – 2012-04-12 11:58:08

+0

@AhsanAshfaq,你是什麼意思的「添加到現有的」? – walther 2012-04-12 11:59:32

0

只需使用索引和直接更新:

dictionary["cat"] = 3 
15

試試這個簡單的函數來添加一個字典項,如果它不存在,或更新,當它存在:

public void AddOrUpdateDictionaryEntry(string key, int value) 
    { 
     if (dict.ContainsKey(key)) 
     { 
      dict[key] = value; 
     } 
     else 
     { 
      dict.Add(key, value); 
     } 
    } 

這是相同的dict [鍵] =值。

+2

與一行中的'dict [key] = value'相同。另外我會打電話功能'AddOrUpdate' – nawfal 2013-11-05 07:51:12

+0

@nawfal他們不一樣,區別在於它首先檢查關鍵字。如果存在,它會添加新值,如果不存在,則會創建新條目。功能名稱雖然好點。 – cubski 2013-11-05 10:11:38

+2

它與'dict [key] = value'相同。你認爲'dict [key] = value'的作用是什麼? – nawfal 2013-11-05 10:13:25

0

字典是一個關鍵值對。通過

dic["cat"] 

,並指定抓住關鍵的價值像

dic["cat"] = 5 
相關問題