C# - 从两个枚举中获取可能的对

时间:2009-12-01 21:11:12

标签: c# linq

从两个枚举中,应用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?.. }

1 个答案:

答案 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);
}