(For convenience, this answer assumes that myList implements an IEnumerable<string> ; if necessary, replace string with the appropriate type.)
If you are using .NET 3.5, use the First() extension method:
string first = myList.First();
If you are not sure if there are any values or not, you can use the FirstOrDefault() method, which will return null (or, more generally, the default value for the item type) for an empty sequence.
You can still do this “long way” without a foreach :
using (IEnumerator<string> iterator = myList.GetEnumerator()) { if (!iterator.MoveNext()) { throw new WhateverException("Empty list!"); } string first = iterator.Current; }
This is pretty ugly though :)
In response to your comment no, the returned iterator will not be positioned first on the first element; it is positioned before the first element. You need to call MoveNext() to transfer it to the first element, and how you can determine the difference between an empty sequence and one with one element.
EDIT: just think about it, I wonder if this extension method is useful:
public static bool TryFirst(this IEnumerable<T> source, out T value) { using (IEnumerator<T> iterator = source.GetEnumerator()) { if (!iterator.MoveNext()) { value = default(T); return false; } value = iterator.Current; return true; } }
Jon skeet
source share