如何在C#中更新存儲在Dictionary中的值?

如何更新字典中的特定鍵的值Dictionary<string, int>this


#1樓

只需指定給定鍵的字典並指定一個新值: spa

myDictionary[myKey] = myNewValue;

#2樓

能夠經過訪問密鑰做爲索引 code

例如: 索引

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2

#3樓

您能夠遵循如下方法: string

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
    int val;
    if (dic.TryGetValue(key, out val))
    {
        // yay, value exists!
        dic[key] = val + newValue;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

您在這裏得到的優點是,只需1次訪問字典便可檢查並獲取相應密鑰的值。 若是使用ContainsKey檢查存在並使用dic[key] = val + newValue;更新值dic[key] = val + newValue; 而後你兩次訪問字典。 it


#4樓

使用LINQ:訪問密鑰的字典並更改值 io

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

#5樓

這可能對你有用: test

場景1:原始類型 date

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};

if(!dictToUpdate.ContainsKey(keyToMatchInDict))
   dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
   dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

場景2:我用於List做爲Value的方法 List

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...

if(!dictToUpdate.ContainsKey(keyToMatch))
   dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
   dictToUpdate[keyToMatch] = objInValueListToAdd;

但願它對須要幫助的人有用。

相關文章
相關標籤/搜索