gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:26:53 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com