C # IEnumerable Get First Entry

I have an IEnumerable list of objects in C #. I can use for each for each cycle and check each object, but in this case, all I want to do is check the first object, is there a way to do this without using a foreach loop?

I tried mylist [0] but it did not work.

thanks

+6
c #
source share
3 answers

(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; } } 
+22
source share

Remember that if the sequence is empty, there can be no “first element”.

  IEnumerable<int> z = new List<int>(); int y = z.FirstOrDefault(); 
+3
source share

If you are not on 3.5:

  using (IEnumerator<Type> ie = ((IEnumerable<Type>)myList).GetEnumerator()) { if (ie.MoveNext()) value = ie.Current; else // doesn't exist... } 

or

  Type value = null; foreach(Type t in myList) { value = t; break; } 
+2
source share

All Articles