5

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?

kerem
  • 2,699
  • 1
  • 32
  • 37
Abhijeet Nagre
  • 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 Interface which resides in the Generic namespace of System.Collections, thus it IS generic. – Abbas Jul 18 '13 at 12:04

3 Answers3

9

You have couple of options:

  1. 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();
    
  2. Or you can use enumerator, make one step and take current element:

    IEnumerator enumerator = enumerable.GetEnumerator();
    enumerator.MoveNext();
    object first = enumerator.Current;
    
Andrei
  • 55,890
  • 9
  • 87
  • 108
1

You have two options here:

  1. 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 the First() method. This is also the most simple implementation.

  2. Use the GetEnumerator() method which gives you an IEnumerator. And from here you can iterate over the collection. Starting with MoveNext(), you can use the Current property to get the first element.

Edit: Andrei was ahead of me.

Abbas
  • 14,186
  • 6
  • 41
  • 72
1

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