C# 获取包含值 x 的字典中的所有键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14146048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all keys in Dictionary containing value x
提问by Elmo
I have this:
我有这个:
Dictionary<integer, string> dict = new Dictionary<integer, string>();
I want to select all the items in the dictionary that contain the value abc
.
我想选择字典中包含 value 的所有项目abc
。
Is there an inbuilt function that lets me do this easily?
是否有内置功能可以让我轻松完成此操作?
采纳答案by Jon Skeet
Well it's reasonablysimple with LINQ:
嗯,使用 LINQ相当简单:
var matches = dict.Where(pair => pair.Value == "abc")
.Select(pair => pair.Key);
Note that this won't be even slightly efficient - it's an O(N)
operation, as it needs to check every entry.
请注意,这甚至不会有点效率 - 这是一个O(N)
操作,因为它需要检查每个条目。
If you need to do this frequently, you may want to consider using another data structure - Dictionary<,>
is specifically designed for fast lookups by key.
如果您需要经常执行此操作,您可能需要考虑使用另一种数据结构 -Dictionary<,>
专为通过 key进行快速查找而设计。
回答by Leonardo
Built-in function? No sorry... but another (not so beautiful) way is to iterate using foreach(KeyValuePair<integer, string> ...
内置功能?不抱歉......但是另一种(不太漂亮)的方法是使用foreach(KeyValuePair<integer, string> ...