开发者

C# -Getting Possible pairs from two enums

From two enums ,what is the way to apply LINQ to get pairs

like

{Red,Car},{Red,Bike},{Green,开发者_JS百科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:

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.)

Then you can write it out like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜