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.
All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array.
You can use the extension method AsEnumerable in Assembly System. Core and System. Linq namespace : List<Book> list = new List<Book>(); return list.
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.
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).
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));
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!
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