开发者

IEnumerable Extension Methods on an Enum

I have an enum(below) that I want to be able to use a LINQ extension meth开发者_高级运维od 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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜