c# - 按键查找字典项后增加字典值

标签 c# dictionary

我有一个定义如下的字典:

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

现在我想通过它的 Key 来细化特定元素,如果缺少此 Key 我想添加新的 Key,如果存在我想增加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.
}

最佳答案

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

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

之所以可行,是因为它与以下内容相同:

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

MSDN:

You can also use the Item property to add new elements by setting the value of a key that does not exist in the Dictionary. When you set the property value, if the key is in the Dictionary, the value associated with that key is replaced by the assigned value. If the key is not in the Dictionary, the key and value are added to the dictionary.


如果您有另一个 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;
    }
}

关于c# - 按键查找字典项后增加字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884918/

相关文章:

c# - Rhino mock 原始方法调用已过时

c# - 如何在碰撞时获取父标签?

javascript - openlayers3移动功能,3.14以上版本不起作用

arrays - 在字典上调用 .sort 会创建新类型吗?

c++ - 通过使用分隔符 C++ 拆分文本来制作二维数组

java - 是否有一个 Java 集合或列表可以在给定对象值的情况下返回对象键?

c# - 压缩大型词典

c# - 了解 SqlMapper.ICustomQueryParameter

c# - 瓷砖在Windows商店应用程序中的存储位置

c# - 如何 : Monitoring file access by another process in Windows?