C# 更改字典中包含键的值

C# 更改字典中包含键的值,c#,for-loop,C#,For Loop,就说我有, Dictionary<string, int> dict = new Dictionary<string, int>(); Dictionary dict=new Dictionary(); 并且在中已经有一些项目: “A”,1 “B”,15 “C”,9 现在,在添加新密钥时,我检查密钥是否已经存在: for(int i = 0; i<n; i++) { if (dict.ContainsKey(newKey[i] ==

就说我有,

Dictionary<string, int> dict = new Dictionary<string, int>();
Dictionary dict=new Dictionary();
并且在中已经有一些项目:

“A”,1

“B”,15

“C”,9

现在,在添加新密钥时,我检查密钥是否已经存在:

for(int i = 0; i<n; i++)
    { 
        if (dict.ContainsKey(newKey[i] == true)
        { 
            //I should add newValue to existing value(sum all of them) of existing key pair
        }
        else
        {
            dict.Add(newKey[i],newValue[i]);
        }
    }

for(int i=0;i最简单的方法是:

for(int i = 0; i < n; i++)
{
    int currentValue;
    // Deliberately ignore the return value
    dict.TryGetValue(newKey[i], out currentValue);
    dict[newKey[i]] = currentValue + newValue[i];
}
for(int i=0;i

这会对每个键执行一个“get”和一个“put”。它使用的事实是
int
的默认值为0-当
TryGetValue
返回false时,
currentValue
将设置为0,这适用于新条目。

最简单的方法是:

for(int i = 0; i < n; i++)
{
    int currentValue;
    // Deliberately ignore the return value
    dict.TryGetValue(newKey[i], out currentValue);
    dict[newKey[i]] = currentValue + newValue[i];
}
for(int i=0;i

这是一个“获取”,然后是一个“放置”对于每个键。它使用的事实是,
int
的默认值为0-当
TryGetValue
返回false时,
currentValue
将设置为0,这适用于新条目。

谢谢,约翰!回答很好,直接且清晰。正是我想要的。谢谢,约翰!回答很好,直接且清晰。正是我想要的寻找。