[ACCEPTED]-How can I retrieve first n elements from Dictionary<string, int>?-dictionary

Accepted answer
Score: 17

Dictionaries are not ordered per se, you can't 7 rely on the "first" actually meaning 6 that. From MSDN: "For enumeration... The 5 order in which the items are returned is 4 undefined."

You may be able to use an 3 OrderedDictionary depending on your platform version, and 2 it's not a particularly complex thing to 1 create as a custom descendant class of Dictionary.

Score: 12

Note that there's no explicit ordering for 6 a Dictionary, so although the following code will 5 return n items, there's no guarantee as to 4 how the framework will determine which n items 3 to return.

using System.Linq;

yourDictionary.Take(n);

The above code returns an IEnumerable<KeyValuePair<TKey,TValue>> containing 2 n items. You can easily convert this to a 1 Dictionary<TKey,TValue> like so:

yourDictionary.Take(n).ToDictionary();
Score: 12

Oftentimes omitting the cast to dictionary 3 won't work:

dictionary = dictionary.Take(n);

And neither will a simple case 2 like this:

dictionary = dictionary.Take(n).ToDictionary();

The surest method is an explicit 1 cast:

dictionary = dictionary.Take(n).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Score: 6

You can't really take the first N elements 5 from a Dictionary<TKey,TValue> because it is not an ordered collection. So 4 it really has no concept of First, Last, etc 3 ... But as others have pointed out, if 2 you just want to take N elements regardless 1 of order the LINQ take function works fine

var map = GetTheDictionary();
var firstFive = map.Take(5);
Score: 3

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
 }

0

More Related questions