从两个枚举中,应用LINQ获取对的方法是什么
像
{红,租车},{红色,自行车},{绿,租车},{绿,自行车},...
public enum Color
{
Red,Green,Blue
}
public enum Vehicle
{
Car,Bike
}
我可以使用像这样的东西
var query = from c in Enum.GetValues(typeof(Color)).AsQueryable()
from c in Enum.GetValues(typeof(Vehicle)).AsQueryable()
select new {..What to fill here?.. }
答案 0 :(得分:9)
不要将c
用作范围变量两次,除非确实需要,否则不要使用AsQueryable
,以非常简单的方式使用匿名类型,并指定范围的类型变量以避免由于Enum.GetValues返回Array
:
var query = from Color c in Enum.GetValues(typeof(Color))
from Vehicle v in Enum.GetValues(typeof(Vehicle))
select new { Color = c, Vehicle = v };
(这相当于在相应的.Cast<Color>
电话上拨打.Cast<Vehicle>
和Enum.GetValues
。)
然后你可以这样写出来:
foreach (var pair in query)
{
Console.WriteLine("{{{0}, {1}}}", pair.Color, pair.Vehicle);
}