Get first element from a dictionary

Note that to call First here is actually to call a Linq extension of IEnumerable, which is implemented by Dictionary<TKey,TValue>. But for a Dictionary, “first” doesn’t have a defined meaning. According to this answer, the last item added ends up being the “First” (in other words, it behaves like a Stack), but that is implementation specific, it’s not the guaranteed behavior. In other words, to assume you’re going to get any defined item by calling First would be to beg for trouble — using it should be treated as akin to getting a random item from the Dictionary, as noted by Bobson below. However, sometimes this is useful, as you just need any item from the Dictionary.

Just use the Linq First():

var first = like.First();
string key = first.Key;
Dictionary<string,string> val = first.Value;

Note that using First on a dictionary gives you a KeyValuePair, in this case KeyValuePair<string, Dictionary<string,string>>.

Note also that you could derive a specific meaning from the use of First by combining it with the Linq OrderBy:

var first = like.OrderBy(kvp => kvp.Key).First();

Leave a Comment