如何在按值过滤时检索键

pau*_*ter 1 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);
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 5

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

var keys = dic.Where(entry => entry.Value > 5)
              .Select(entry => entry.Key);
Run Code Online (Sandbox Code Playgroud)

请注意,这种方法对任何方法都没有问题IDictionary<,>- 事实上你有一个ConcurrentDictionary<,>与此无关的事实.