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

2020-04-01 12:03发布

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?

4条回答
叼着烟拽天下
2楼-- · 2020-04-01 12:47

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 :)

查看更多
劳资没心,怎么记你
3楼-- · 2020-04-01 12:54

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5
查看更多
Summer. ? 凉城
4楼-- · 2020-04-01 12:59

Just use the indexer and update directly:

dictionary["cat"] = 3
查看更多
倾城 Initia
5楼-- · 2020-04-01 13:00

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.

查看更多
登录 后发表回答