简体   繁体   English

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

[英]C# -Getting Possible pairs from two enums

From two enums ,what is the way to apply LINQ to get pairs 从两个枚举中,应用LINQ获取对的方法是什么

like 喜欢

{Red,Car},{Red,Bike},{Green,Car},{Green,Bike},... {红,租车},{红,自行车},{绿,租车},{绿,自行车},...

public enum Color
{
    Red,Green,Blue
}

public enum Vehicle
{
    Car,Bike
}

can i use something like 我可以使用类似的东西吗?

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

Don't use c as the range variable twice, don't use AsQueryable unless you really need to, use an anonymous type in a really simple way, and specify the type of the range variable to avoid problems due to Enum.GetValues just returning Array : 不要使用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 };

(That's equivalent to calling .Cast<Color> and .Cast<Vehicle> on the respective Enum.GetValues calls.) (这相当于在相应的Enum.GetValues调用上调用.Cast<Color>.Cast<Vehicle> 。)

Then you can write it out like this: 然后你可以这样写出来:

foreach (var pair in query)
{
    Console.WriteLine("{{{0}, {1}}}", pair.Color, pair.Vehicle);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM