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?
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.
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.
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;
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 the First() method. This is also the most simple implementation.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With