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
?

- 2,699
- 1
- 32
- 37

- 876
- 1
- 11
- 21
-
Attach code so we can help you better. AFAIK `IEnumerable
` is not generic – Kamil Budziewski Jul 18 '13 at 11:57 -
2@wudzik IEnumerable
is the implementation of the IEnumerable – Abbas Jul 18 '13 at 12:04Interface which resides in the Generic namespace of System.Collections, thus it IS generic.
3 Answers
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 useobject
: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;

- 55,890
- 9
- 87
- 108
You have two options here:
Follow the question that @Danier Gimenez suggested and make use of the
Cast<TResult>
method. After the cast you get a generic enumerable on which you can apply theFirst()
method. This is also the most simple implementation.Use the
GetEnumerator()
method which gives you anIEnumerator
. And from here you can iterate over the collection. Starting withMoveNext()
, you can use theCurrent
property to get the first element.
Edit: Andrei was ahead of me.

- 14,186
- 6
- 41
- 72
it is simple look this sample code
IEnumerable collection; --- fill collection here--- collection.OfType().ToList() or collection.OfType().ToArray collection.OfType().ToList() or collection.OfType().ToArray() it's filter the (int/MyClass) types object and convert it to a list or array

- 21
- 1