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

use*_*675 2 c# linq

从两个枚举中,应用LINQ获取对的方法是什么

喜欢

{红,租车},{红,自行车},{绿,租车},{绿,自行车},...

public enum Color
{
    Red,Green,Blue
}

public enum Vehicle
{
    Car,Bike
}
Run Code Online (Sandbox Code Playgroud)

我可以使用类似的东西吗?

var query = from c in Enum.GetValues(typeof(Color)).AsQueryable() 
            from c in Enum.GetValues(typeof(Vehicle)).AsQueryable()    
            select new {..What to fill here?.. }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 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 };
Run Code Online (Sandbox Code Playgroud)

(这相当于呼叫.Cast<Color>.Cast<Vehicle>相应的Enum.GetValues呼叫.)

然后你可以这样写出来:

foreach (var pair in query)
{
    Console.WriteLine("{{{0}, {1}}}", pair.Color, pair.Vehicle);
}
Run Code Online (Sandbox Code Playgroud)