I\'m using a System.Collections.Generic.Dictionary
.
I want to return the first key from this dictionary. I tried dic.Keys[0]
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();
Seems a bit over the top, but how about
foreach (<Type> k in dic.Keys)
return k;
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
.)
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.
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.