Get first key from Dictionary<string, string>

.net, c#, collections, dictionary

Solution

Assuming you're using .NET 3.5:

dic.Keys.First();

Note that there's no guaranteed order in which key/value pairs will be iterated over in a dictionary. You may well find that in lots of cases you get out the first key that you put into the dictionaries - but you absolutely must not rely on that. As Skirwan says, there isn't really a notion of "first". Essentially the above will give you "a key from the dictionary" - that's about all that's guaranteed.

(If you don't know whether the dictionary is empty or not, you could use `FirstOrDefault`.)

Problem

I'm using a `System.Collections.Generic.Dictionary<string, string>`. I want to return the first key from this dictionary. I tried `dic.Keys[0]` but the only thing I have on the `Keys` property (which is a `KeyCollection` object) is an enumerator. Do I have to enumerate through all the keys to get the first one?

Original source

Related problems