Converting Array to IEnumerable

后端 未结 2 1411
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 00:36

To my surprise, I get the following statement:

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

to

2条回答
  •  既然无缘
    2021-02-13 00:49

    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!

提交回复
热议问题