枚举上的IEnumerable扩展方法 [英] IEnumerable Extension Methods on an Enum

查看:134
本文介绍了枚举上的IEnumerable扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 枚举套装(下)我想要使用LINQ扩展方法{
Hearts = 0,
钻石= 1,
俱乐部= 2,
Spades = 3
}
pre>

Enum.GetValues(...)是返回类型System.Array,但我似乎无法访问ToList()扩展或其他任何东西



我只是想写一些类似...

  foreach(西装在Enum.GetValues(typeof(西装))。选择(x => x).Where(x => x!= param)){} 

有没有我错过的东西,还是有人向我解释为什么这是不可能的?



谢谢。

解决方案

Enum.GetValues 返回 System.Array System.Array 只实现 IEnumerable IEnumerable< T> 所以你需要使用 Enumerable.OfType 扩展方法将 IEnumerable 转换为 IEnumerable<西装> 像这样:

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

编辑:我删除了 IEnumerable 。选择,因为它是一个多余的投影,没有任何有意义的翻译。您可以自由过滤从 OfType< T> 返回的 IEnumerable< Suit> 。 $ b

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.

解决方案

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

这篇关于枚举上的IEnumerable扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆