IEnumerable Extension Methods on an Enum

后端 未结 2 1143
遇见更好的自我
遇见更好的自我 2020-12-28 14:36

I have an enum(below) that I want to be able to use a LINQ extension method on.

enum Suit{
    Hearts = 0,
    Diamonds = 1,
    Clubs = 2,
    Spades = 3
}
         


        
相关标签:
2条回答
  • 2020-12-28 15:04

    Enum.GetValues returns a System.Array and System.Array only implements IEnumerable rather than IEnumerable<T> so you will need to use the Enumerable.OfType extension method to convert the IEnumerable to IEnumerable<Suit> like this:

    Enum.GetValues(typeof(Suit))
                .OfType<Suit>()
                .Where(x => x != param);
    

    Edit: I removed the call to IEnumerable.Select as it was a superfluous projection without any meaningful translation. You can freely filter the IEnumerable<Suit> that is returned from OfType<T>.

    0 讨论(0)
  • 2020-12-28 15:10

    Array implements IEnumerable so you'll need to use Cast<Suit> or OfType<Suit> to get the IEnumerble<T> extensions like ToList();

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