I often want to grab the first element of an IEnumerable<T> in .net, and I haven’t found a nice way to do it. The best I’ve come up with is:
foreach(Elem e in enumerable) { // do something with e break; }
Yuck! So, is there a nice way to do this?
If you can use LINQ you can use:
This will throw an exception though if enumerable is empty: in which case you can use:
FirstOrDefault()will returndefault(T)if the enumerable is empty, which will benullfor reference types or the default ‘zero-value’ for value types.If you can’t use LINQ, then your approach is technically correct and no different than creating an enumerator using the
GetEnumeratorandMoveNextmethods to retrieve the first result (this example assumes enumerable is anIEnumerable<Elem>):Joel Coehoorn mentioned
.Single()in the comments; this will also work, if you are expecting your enumerable to contain exactly one element – however it will throw an exception if it is either empty or larger than one element. There is a correspondingSingleOrDefault()method that covers this scenario in a similar fashion toFirstOrDefault(). However, David B explains thatSingleOrDefault()may still throw an exception in the case where the enumerable contains more than one item.Edit: Thanks Marc Gravell for pointing out that I need to dispose of my
IEnumeratorobject after using it – I’ve edited the non-LINQ example to display theusingkeyword to implement this pattern.