[英]How can I retrieve first n elements from Dictionary<string, int>?
有没有办法从C#中的Dictionary中检索前n个元素?
Dictionaries are not ordered per se , you can't rely on the "first" actually meaning that. 字典本身并不是有序的,你不能依赖“第一”的含义。 From MSDN: "For enumeration... The order in which the items are returned is undefined."
来自MSDN:“对于枚举...返回项目的顺序是未定义的。”
You may be able to use an OrderedDictionary depending on your platform version, and it's not a particularly complex thing to create as a custom descendant class of Dictionary. 您可以根据平台版本使用OrderedDictionary ,并且创建Dictionary的自定义后代类并不是特别复杂。
Note that there's no explicit ordering for a Dictionary
, so although the following code will return n
items, there's no guarantee as to how the framework will determine which n
items to return. 请注意,没有
Dictionary
显式排序,因此尽管以下代码将返回n
项目,但无法保证框架将如何确定要返回的n
项目。
using System.Linq;
yourDictionary.Take(n);
The above code returns an IEnumerable<KeyValuePair<TKey,TValue>>
containing n
items. 上面的代码返回包含
n
项目的IEnumerable<KeyValuePair<TKey,TValue>>
。 You can easily convert this to a Dictionary<TKey,TValue>
like so: 您可以轻松地将其转换为
Dictionary<TKey,TValue>
如下所示:
yourDictionary.Take(n).ToDictionary();
You can't really take the first N elements from a Dictionary<TKey,TValue>
because it is not an ordered collection. 你不能真正从
Dictionary<TKey,TValue>
获取前N个元素Dictionary<TKey,TValue>
因为它不是有序集合。 So it really has no concept of First, Last, etc ... But as others have pointed out, if you just want to take N elements regardless of order the LINQ take function works fine 所以它真的没有First,Last等概念......但正如其他人所指出的那样,如果你只是想采用N个元素而不管顺序LINQ take函数工作正常
var map = GetTheDictionary();
var firstFive = map.Take(5);
Oftentimes omitting the cast to dictionary won't work: 通常省略演员到字典是行不通的:
dictionary = dictionary.Take(n);
And neither will a simple case like this: 这样的简单案例也不会:
dictionary = dictionary.Take(n).ToDictionary();
The surest method is an explicit cast: 最可靠的方法是显式转换:
dictionary = dictionary.Take(n).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Could use Linq for example? 可以用Linq为例吗?
var dictionary = new Dictionary<string, int>();
/// Add items to dictionary
foreach(var item in dictionary.Take(5))
{
// Do something with the first 5 pairs in the dictionary
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.