在字典中增加数值 [英] Incrementing a numerical value in a dictionary

查看:136
本文介绍了在字典中增加数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码在字典中增加或插入一个值.如果我要递增的键不存在,我想将其值设置为1.

I'm using the code below to either increment or insert a value in a dictionary. If the key I'm incrementing doesn't exist I'd like to set its value to 1.

 public void IncrementCount(Dictionary<int, int> someDictionary, int id)
 {  
     int currentCount;
     if (someDictionary.TryGetValue(id, out currentCount))
     {
         someDictionary[id] = currentCount + 1;
     }
     else
     {
         someDictionary[id] = 1;
     }
 }

这是这样做的合适方法吗?

Is this an appropriate way of doing so?

推荐答案

事实证明,使用ConcurrentDictionary具有合理的upsert方法:AddOrUpdate是很有意义的.

As it turns out it made sense to use the ConcurrentDictionary which has the handy upsert method: AddOrUpdate.

所以,我只是用过:

someDictionary.AddOrUpdate(id, 1, (id, count) => count + 1);  

这篇关于在字典中增加数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆