Get first key from Dictionary<string, string>

103,496

Solution 1

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.)

Solution 2

The idea of 'first' doesn't really apply to a dictionary, as there's no ordering on the entries; any insert or remove is allowed to radically change the order of the keys.

Solution 3

Firstly, no, you do not have to enumerate all of the entries — just enumerate the first item:

IEnumerator enumerator = dictionary.Keys.GetEnumerator();
enumerator.MoveNext();
object first = enumerator.Current;

Ideally one would check that the MoveNext() actually succeeded (it returns a bool) otherwise the call to Current may throw.

Please also note that the order of a dicitonary is not specified. This means that the 'first' item may in fact be any key, may be different on subsequent calls (though in practice will not) and will certainly change as items are added and removed from the dictionary.

Solution 4

Seems a bit over the top, but how about

foreach (<Type> k in dic.Keys)
    return k;

Solution 5

we can using linq technology

var key = dic.Take(1).Select(d => d.Key).First()

or we can use another search

var myList = dic.Take(1).Where(d => d.Key.Contains("Heaven")).ToList();
Share:
103,496
Michel
Author by

Michel

Updated on July 23, 2021

Comments

  • Michel
    Michel almost 3 years

    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?