如何在按值过滤时检索键

时间:2015-01-29 18:45:12

标签: c# .net-4.0 concurrentdictionary

ConcurrentDictionary<int, int> dic = new ConcurrentDictionary<int, int>();
dic.AddOrUpdate(1, 2, (s, i) => 0);
dic.AddOrUpdate(2, 3, (s, i) => 0);
dic.AddOrUpdate(3, 1, (s, i) => 0);
dic.AddOrUpdate(4, 7, (s, i) => 0);

我只想选择值大于5的键。我该怎么做?

1 个答案:

答案 0 :(得分:5)

只需选择条目,根据值进行过滤,然后投射到按键:

var keys = dic.Where(entry => entry.Value > 5)
              .Select(entry => entry.Key);

请注意,此方法适用于任何IDictionary<,> - 您有ConcurrentDictionary<,>这一事实与此无关。