枚举上的IEnumerable扩展方法 [英] IEnumerable Extension Methods on an Enum
问题描述
枚举套装(下)我想要使用LINQ扩展方法{
pre>
Hearts = 0,
钻石= 1,
俱乐部= 2,
Spades = 3
}
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>
。 $ bI 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 aSystem.Array
andSystem.Array
only implementsIEnumerable
rather thanIEnumerable<T>
so you will need to use theEnumerable.OfType
extension method to convert theIEnumerable
toIEnumerable<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 theIEnumerable<Suit>
that is returned fromOfType<T>
.这篇关于枚举上的IEnumerable扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!