2009-12-01 65 views
2

兩個枚舉-Getting可能對,什麼是應用LINQ得到的方式對C#從兩個枚舉

{紅,租車},{紅,自行車},{綠色汽車},{綠,自行車},...

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?.. } 

回答

9

不要使用c的範圍變量TWIC即,不使用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 }; 

(這相當於呼籲各Enum.GetValues電話.Cast<Color>.Cast<Vehicle>。)

然後,你可以寫出來是這樣的:

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

閱兵式速度!在我輸入完成之前更正了投射問題。 – 2009-12-01 21:20:52

+0

:)其實我不知道AsQueryable的實際用法是什麼,我從你的書中跳過了那章。我必須讀它。 – user215675 2009-12-01 21:25:38

+0

Cast()的Type()哪個好? – user215675 2009-12-01 21:27:08