How to update value of a key in dictionary in c#? [duplicate]

拟墨画扇 提交于 2019-12-01 13:46:07

问题


I have the following code in c# , basically it's a simple dictionary with some keys and their values.

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

I want to update the key 'cat' with new value 5.
How could I do this?


回答1:


Have you tried just

dictionary["cat"] = 5;

:)

Update

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

Beware of non-existing keys :)




回答2:


Try this simple function to add an dictionary item if it does not exist or update when it exists:

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

This is the same as dict[key] = value.




回答3:


Just use the indexer and update directly:

dictionary["cat"] = 3



回答4:


Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5


来源:https://stackoverflow.com/questions/10123043/how-to-update-value-of-a-key-in-dictionary-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!