我有一个字典定义如下:
Dictionary<string, double> collection = new Dictionary<string, double>();
现在我想通过它的Key
来细化特定的元素,如果这个Key
缺失,我想添加新的Key
, Value
,如果存在,我想增加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.
}
您可以使用索引器将其更新为增量值:
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;
}
}
我不明白为什么人们继续用字典反模式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;
_collection[str]
将为您提供与[]
中指定的键对应的值,因此,_collection[str]++
将增加与1
对应的值
你只需要像下面这样改变else部分:
string str;
if (!_collection.ContainsKey(str))
_collection.Add(str, 0);
else
{
_collection[str]++;
}
在c# 7.0中,最简单和最有效的方法是:
_collection.TryGetValue(str, out double value);
_collection[str] = value++;