tags:

views:

133

answers:

1

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

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?.. }
+8  A: 

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);
}
Jon Skeet
Senor Speed! Corrected the casting issue before I finished typing.
gWiz
:) Actually I do not know what is the actual use of AsQueryable.I skipped that chapter from your book.I have to read it.
Cast() ofType() which one is good?
By the way how to apply index value to get {1,Red,Car} ,{2,Red,Bike},...
@threadpool: Cast/OfType: It depends if you want to skip values of different types or throw an exception. If they really *should* be the expected type (i.e. anything else represents a bug) then use Cast. As for indexing - you can use dot notation and a different overload of Select - unfortunately I don't have time to show an example right now. You may want to ask that as a different question so that someone else can answer it.
Jon Skeet