我尝试将小数点添加到ConcurrentDictionary
内的列表中
ConcurrentDictionary<string, List<decimal>> fullList =
new ConcurrentDictionary<string, List<decimal>>();
public void AddData(string key, decimal value)
{
if (fullList.ContainsKey(key))
{
var partialList = fullList[key];
partialList.Add(value);
}
else
{
fullList.GetOrAdd(key, new List<decimal>() { value });
}
}
从技术上讲,上面的代码对我有用,但之所以这样做,是因为我不知道如何添加和更新GetOrAdd
方法。我的问题是,考虑到我的更新是将一个项目添加到现有列表的末尾,我如何同时使用该方法?
最佳答案
您可以为此使用AddOrUpdate
方法,如下所示:
fullList.AddOrUpdate(key,
new List<decimal>() { value },
(key,list) =>
{
list.Add(value);
return list;
});
本质上,当key
丢失时,将创建一个仅包含一个元素value
的新列表。否则,我们将添加到与当前key
和value
关联的列表中,然后返回列表。有关此方法的文档,请查看here。
关于c# - 将不同的值添加到并发字典中的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64295225/