tags:

views:

863

answers:

4

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

+4  A: 

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();
LukeH
I'm getting following error after using the above method - Error 38 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string,int>>' to 'System.Collections.Generic.Dictionary<string,int>'. An explicit conversion exists (are you missing a cast?) E:\Assignments\Hotel search web application\Tavisca.Budgie\Tavisca.Budgie.Ui\Models\UserDataAccess.cs 1149 24 Tavisca.Budgie.Ui
buntykawale
Seems like you are trying to put the elements into a new dictonary. You will have to use Enumerable.ToDictonary() to get this done.
Daniel Brückner
@buntykawale, As Daniel mentioned, the Take method returns an IEnumerable, not a Dictionary. I've updated my answer to show how to convert back to a Dictionary.
LukeH
+4  A: 

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
 }
Svish
+17  A: 

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.

annakata
+7  A: 

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