简体   繁体   English

从字典中获取一系列键的有效方法

[英]Efficient way to get a range of Keys from Dictionary

I have a Dictionary that for most operations I just need to retrieve a single entry by key, but for a few operations I will need to work with the entries associated with a range of keys. 我有一个Dictionary ,对于大多数操作我只需要通过键检索单个条目,但是对于一些操作,我将需要处理与一系列键相关联的条目。 The way that occurs to me to do this is to use GetKeys and a FindAll that will match the range I am interested in, but was wondering if someone could suggest a better method. 我这样做的方法是使用GetKeys和一个匹配我感兴趣的范围的FindAll ,但是想知道是否有人可以提出更好的方法。

A Dictionary which is implemented as a hash table is not particularly suited to efficiently perform range selection operations on keys. 实现为散列表的Dictionary不是特别适合于有效地对密钥执行范围选择操作。 You'll have to visit all keys to find all of them in a specified range. 您必须访问所有键才能在指定范围内找到所有键。 A nice way to accomplish it is to query its collection of keys with a simple LINQ expression. 完成它的一个好方法是使用简单的LINQ表达式查询其键集合。

A SortedList or SortedDictionary would have the items sorted so you can try to get the key at the bottom of your range then traverse the elements to the top of your range. SortedListSortedDictionary将对项目进行排序,以便您可以尝试获取范围底部的键,然后将元素遍历到范围的顶部。

Using binary search on a SortedList will give you the index of the key matching the bottom of your range, or the nearest higher value. SortedList上使用二进制搜索将为您提供与范围底部匹配的键的索引,或最接近的更高值。 See How to perform a binary search on IList<T>? 请参阅如何在IList <T>上执行二进制搜索?

Like you said, a find all would work. 就像你说的,一个发现都会起作用。 Maybe something like; 也许是这样的;

dictionary.FindAll(entry => multipleStrings.Contains(entry.Key));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM