How to get the first element of IEnumerable (non-generic)?

c#

Solution

You have couple of options:

If you know that all objects in your enumerable are of the same type, you can cast it to the generic `IEnumerable<YourType>`. In worst case you can always use `object`:

object first = enumerable.Cast<object>().First();

Or you can use enumerator, make one step and take current element:

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

Problem

If I have a generic `IEnumerable<int>`. I can simply apply `ToList()` or `ToArray()` or `FirstOrDefault()` to it. How to apply these methods to a non-generic `IEnumerable`?

Original source

Related problems