如何在 C# 中更新存储在字典中的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1243717/
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-06 14:08:11  来源:igfitidea点击:

How to update the value stored in Dictionary in C#?

c#dictionary

提问by Amit

How to update value for a specific key in a dictionary Dictionary<string, int>?

如何更新字典中特定键的值Dictionary<string, int>

采纳答案by ccalboni

Just point to the dictionary at given key and assign a new value:

只需指向给定键的字典并分配一个新值:

myDictionary[myKey] = myNewValue;

回答by Amit

It's possible by accessing the key as index

可以通过访问键作为索引

for example:

例如:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2

回答by Matthew

Here is a way to update by an index much like foo[x] = 9where xis a key and 9 is the value

这是一种通过索引更新的方法,就像foo[x] = 9where xis a key and 9 is the value

var views = new Dictionary<string, bool>();

foreach (var g in grantMasks)
{
    string m = g.ToString();
    for (int i = 0; i <= m.Length; i++)
    {
        views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
    }
}

回答by max_force

You can follow this approach:

您可以遵循以下方法:

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);
    }
}

The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary. If you use ContainsKeyto check the existance and update the value using dic[key] = val + newValue;then you are accessing the dictionary twice.

您在这里获得的优势是,您只需 1 次访问字典即可检查并获取相应键的值。如果您ContainsKey用来检查存在性并使用更新值,dic[key] = val + newValue;那么您将访问字典两次。

回答by INT_24h

Use LINQ: Access to dictionary for the key and change the value

使用 LINQ:访问键的字典并更改值

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

回答by Mister Pitt

This may work for you:

这可能对您有用:

Scenario 1: primitive types

场景 1:原始类型

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;

Scenario 2: The approach I used for a List as Value

场景 2:我用于 List as Value 的方法

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;

Hope it's useful for someone in need of help.

希望对需要帮助的人有用。

回答by Vlad Kaponir

  1. update- modify existent only. To avoid side effect of indexer use:

    int val;
    if (dic.TryGetValue(key, out val))
    {
        // key exist
        dic[key] = val;
    }
    
  2. update or (addnew if value doesn't exist in dic)

    dic[key] = val;
    

    for instance:

    d["Two"] = 2; // adds to dictionary because "two" not already present
    d["Two"] = 22; // updates dictionary because "two" is now present
    
  1. 更新- 仅修改现有。为避免索引器使用的副作用:

    int val;
    if (dic.TryGetValue(key, out val))
    {
        // key exist
        dic[key] = val;
    }
    
  2. 更新或(如果 dic 中不存在值,则添加新的)

    dic[key] = val;
    

    例如:

    d["Two"] = 2; // adds to dictionary because "two" not already present
    d["Two"] = 22; // updates dictionary because "two" is now present