Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array to IEnumerable<T>

To my surprise, I get the following statement:

public static IEnumerable<SomeType> AllEnums 
  => Enum.GetValues(typeof(SomeType));

to complain about not being able to convert from System.Array to System.Collection.Generic.IEnumerable. I thought that the latter was inheriting from the former. Apparently I was mistaken.

Since I can't LINQ it or .ToList it, I'm not sure how to deal with it properly. I'd prefer avoiding explicit casting and, since it's a bunch of values for an enum, I don't think as SomeType-ing it will be of much use, neither.

like image 897
Konrad Viltersten Avatar asked Jan 02 '15 15:01

Konrad Viltersten


People also ask

Is array IEnumerable C#?

All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array.

How do I make a list IEnumerable?

You can use the extension method AsEnumerable in Assembly System. Core and System. Linq namespace : List<Book> list = new List<Book>(); return list.

What is IEnumerable interface 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.

What is the return type of IEnumerable?

IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).


2 Answers

The general Array base class is not typed, so it does not implement any type-specific interfaces; however, a vector can be cast directly - and GetValues actually returns a vector; so:

public static IEnumerable<SomeType> AllEnums
    = (SomeType[])Enum.GetValues(typeof(SomeType));

or perhaps simpler:

public static SomeType[] AllEnums 
    = (SomeType[])Enum.GetValues(typeof(SomeType));
like image 66
Marc Gravell Avatar answered Sep 18 '22 19:09

Marc Gravell


I thought that the latter was inheriting from the former.

Enum.GetValues returns Array, which implements the non-generic IEnumerable, so you need to add a cast:

public static IEnumerable<SomeType> AllEnums = Enum.GetValues(typeof(SomeType))
    .Cast<SomeType>()
    .ToList(); 

This works with LINQ because Cast<T> extension method is defined for the non-generic IEnumerable interface, not only on IEnumerable<U>.

Edit: A call of ToList() avoid inefficiency associated with walking multiple times an IEnumerable<T> produced by LINQ methods with deferred execution. Thanks, Marc, for a great comment!

like image 45
Sergey Kalinichenko Avatar answered Sep 21 '22 19:09

Sergey Kalinichenko