Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

dictionary

Is there a way to retrieve first n elements from a Dictionary in C#?

like image 493
buntykawale Avatar asked May 05 '09 11:05

buntykawale


2 Answers

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.

like image 199
annakata Avatar answered Sep 30 '22 12:09

annakata


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();
like image 39
LukeH Avatar answered Sep 30 '22 11:09

LukeH