Converting Array to IEnumerable

后端 未结 2 1371
南方客
南方客 2021-02-13 00:15

To my surprise, I get the following statement:

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

to

相关标签:
2条回答
  • 2021-02-13 01:00

    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));
    
    0 讨论(0)
  • 2021-02-13 01:06

    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!

    0 讨论(0)
提交回复
热议问题