如何在c#中更新字典中键的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10123043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:30:50  来源:igfitidea点击:

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

c#c#-4.0dictionarykey-value

提问by Ahsan Ashfaq

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

我在 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);

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

我想用新值5更新键 'cat' 。
我怎么能这样做?

回答by J0HN

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

当心不存在的密钥:)

回答by yamen

Just use the indexer and update directly:

只需使用索引器并直接更新:

dictionary["cat"] = 3

回答by cubski

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.

这与 dict[key] = value 相同。

回答by Nikhil Agrawal

Dictionary is a key value pair. Catch Key by

字典是一个键值对。抓住关键

dic["cat"] 

and assign its value like

并分配其值,例如

dic["cat"] = 5