Converting Array to IEnumerable<T>

☆樱花仙子☆ 提交于 2019-12-21 07:54:27

问题


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.


回答1:


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));



回答2:


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!



来源:https://stackoverflow.com/questions/27744199/converting-array-to-ienumerablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!