Convert array to IEnumerable <T>

To my surprise, I get the following statement:

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

to complain about the inability to convert from System.Array to System.Collection.Generic.IEnumerable. I thought the latter inherited from the former. Apparently, I was wrong.

Since I can't LINQ this or .TLList, I'm not sure how to handle this. I would prefer to avoid explicit casting, and since this is a bunch of values ​​to list, I don't think SomeType-ing will be very useful.

+7
arrays casting c # type-conversion ienumerable
source share
2 answers

The common base class Array not introduced, so it does not implement any interfaces of a specific type; however, the vector can be directly reset - and GetValues actually returns the vector; So:

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

or maybe simpler:

 public static SomeType[] AllEnums = (SomeType[])Enum.GetValues(typeof(SomeType)); 
+12
source share

I thought the latter is inherited from the former.

Enum.GetValues returns an Array that implements a non-generic IEnumerable , so you need to add a listing:

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

This works with LINQ because the Cast<T> extension method is defined for a non-general IEnumerable interface, and not just for IEnumerable<U> .

Edit: Calling ToList() avoids the inefficiency associated with walking multiple times with IEnumerable<T> created by LINQ methods with deferred execution. Thanks Mark for a great comment!

+4
source share

All Articles