Converting Array to IEnumerable

后端 未结 2 1374
南方客
南方客 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: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 AllEnums = Enum.GetValues(typeof(SomeType))
        .Cast()
        .ToList(); 
    

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

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

提交回复
热议问题