有没有办法从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."
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.
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.
using System.Linq;
yourDictionary.Take(n);
The above code returns an IEnumerable<KeyValuePair<TKey,TValue>>
containing n
items. You can easily convert this to a Dictionary<TKey,TValue>
like so:
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. 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
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?
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.