Hi all, Is there a way to retrieve first n elements from a Dictionary in C#?
views:
863answers:
4Note 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();
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
}
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.
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);