获取字典中包含值x的所有键 [英] Get all keys in Dictionary containing value x
本文介绍了获取字典中包含值x的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个:
Dictionary<integer, string> dict = new Dictionary<integer, string>();
我想选择字典中包含值abc
的所有项目.
I want to select all the items in the dictionary that contain the value abc
.
有内置的函数可以让我轻松地做到这一点吗?
Is there an inbuilt function that lets me do this easily?
推荐答案
使用LINQ,合理很简单:
Well it's reasonably simple with LINQ:
var matches = dict.Where(pair => pair.Value == "abc")
.Select(pair => pair.Key);
请注意,这甚至效率不高-这是O(N)
操作,因为它需要检查每个条目.
Note that this won't be even slightly efficient - it's an O(N)
operation, as it needs to check every entry.
如果您需要经常执行此操作,则可能要考虑使用其他数据结构-Dictionary<,>
是专门为通过键快速查找而设计的.
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.
这篇关于获取字典中包含值x的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文