按键查找字典项后增加字典值

时间:2015-10-01 10:11:37

标签: c# dictionary

我的词典定义如下:

Dictionary<string, double> collection = new Dictionary<string, double>();

现在我希望通过它Key来细化特定元素,如果缺少此Key我想添加新的KeyValue,如果存在,我想要增加Value

string str;
if (!collection.ContainsKey(str))
    _collection.Add(str, 0);
else
{
    KeyValuePair<string, double> item = collection.FirstOrDefault(x => x.Key == str);
    // Here i want to update my Value.
}

4 个答案:

答案 0 :(得分:3)

您可以使用indexer使用递增的值更新它:

if (!collection.ContainsKey(str))
    collection.Add(str, 0);
else
{
    collection[str]++;
}

这是有效的,因为它与:

相同
collection[str] = collection[str] + 1;

MSDN:

  

您还可以使用Item属性通过设置添加新元素   字典中不存在的键的值。   设置属性值时,如果键位于,则为   字典,与该键关联的值是   替换为指定值。如果钥匙不在   字典,键和值被添加到   字典。

如果您有另一个KeyValuePair<string, double>集合作为评论,并且您希望在密钥存在时使用这些值更新字典,或者如果密钥不存在则添加它们:

foreach(KeyValuePair<string, double> pair in otherCollection)
{
    if (!collection.ContainsKey(pair.Key))
        collection.Add(pair.Key, 0);
    else
    {
        collection[pair.Key] = pair.Value;
    }
}

答案 1 :(得分:2)

我不明白为什么人们继续使用该字典反模式if (dic.ContansKey(key)) value = dic[key]发布代码。最有效和正确的方法就是这样

string str;
double value;
if (!_collection.TryGetValue(str, out value))
{
    // set the initial value
    _collection.Add(str, 0);
}
else
{
    // update the existing value
    value++;    
    _collection[str] = value;
}

请注意,注释仅包含在示例中,通常只是

if (!_collection.TryGetValue(str, out value))
    _collection.Add(str, 0);
else
    _collection[str] = value + 1;

答案 2 :(得分:1)

_collection[str]会为您提供与[]中指定的密钥相对应的值,因此,_collection[str]++将按1

增加与密钥对应的值

您必须更改else部分,如下所示:

string str;
if (!_collection.ContainsKey(str))
    _collection.Add(str, 0);
else
{
   _collection[str]++;
}

答案 3 :(得分:0)

对于C#7.0,最简单,最有效的方法是:

_collection.TryGetValue(str, out double value);
_collection[str] = value++;
相关问题