IEnumerable Extension Methods on an Enum

时光毁灭记忆、已成空白 提交于 2019-12-18 11:43:18

问题


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
}

Enum.GetValues(...) is of return type System.Array, but I can't seem to get access to a ToList() extension or anything else of that sort.

I'm just looking to write something like...

foreach(Suit s in Enum.GetValues(typeof(Suit)).Select(x=>x).Where(x=> x != param)){}

Is there something I'm missing, or can someone explain to me why this isn't possible?

Thanks.


回答1:


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>.




回答2:


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



来源:https://stackoverflow.com/questions/1752194/ienumerable-extension-methods-on-an-enum

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