Is there a way to retrieve first n elements from a Dictionary in C#?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With