How can I retrieve first n elements from Dictionary<string, int>?

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();

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);

Tags:

C#

Dictionary