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

Ahs*_*faq 21 c# dictionary key-value c#-4.0

我在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);
Run Code Online (Sandbox Code Playgroud)

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

J0H*_*0HN 34

你尝试过吗?

dictionary["cat"] = 5;
Run Code Online (Sandbox Code Playgroud)

:)

更新

dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;
Run Code Online (Sandbox Code Playgroud)

小心不存在的键 :)


cub*_*ski 18

尝试使用此简单函数添加字典项(如果它不存在)或更新它存在时:

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

这与dict [key] = value相同.

  • 这与一行中的`dict [key] = value`相同.我还会调用函数`AddOrUpdate` (2认同)
  • 这与`dict [key] = value`相同.你觉得`dict [key] = value`怎么办? (2认同)