如何在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;

但愿它对须要帮助的人有用。

相关文章
相关标签/搜索