Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 620
Abhijeet Nagre Avatar asked Jul 18 '13 11:07

Abhijeet Nagre


People also ask

How do I get the first item in IEnumerable?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.

What is IEnumerable <> in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.


3 Answers

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;
    
like image 140
Andrei Avatar answered Nov 01 '22 12:11

Andrei


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.

like image 30
Abbas Avatar answered Nov 01 '22 12:11

Abbas


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

like image 26
mazhar zarsaw Avatar answered Nov 01 '22 11:11

mazhar zarsaw