2009-06-17 67 views
8

這確實應該是很容易的,但我不能工作了我自己,界面不夠直觀... :(選擇所有子對象Linq中

比方說,我有一個State表,我想從多個States選擇所有Counties在SQL中,這將是:

select c.* 
    from State s join County c on c.StateCode = s.StateCode 
where s.TimeZone = -5 -- or some other criteria 

上面的例子就足以瑣碎轉換的LINQ靜態上下文:

var q = MyDataContext.GetTable<County>().Where(c => c.State.TimeZone = -5); 

但是,在它開始變得複雜的是,如果我想要更多的上下文敏感的查詢,如下面的:

public static List<County> GetCountiesForStates(List<State> states) { 
    // gotta do something to return all the counties for all these states 
} 

現在我可以做一些像這樣的方法中:

var q = MyDataContext.GetTable<County>().Where(c => states.Contains(c.State)); 

但IMO (a)我必須得到一個靜態的MyDataContext而不是使用State對象的隱式數據上下文,並且(b)你向後工作,並且如果開始複雜化查詢,它會變得更加醜陋。

是否與啓動查詢的一種方式:

var q = states... // or "from s in states..." 

出於本能,我想相信你能做到這一點,但我還沒有找到路...

回答

26

你可以這樣做:

var q = from c in countries 
     from s in c.States 
     where c.Property == Something 
     select s; 

這會給你所有國家的所有國家的枚舉。這翻譯成以下內容:

var q = countries.Where(x => c.Property == Something).SelectMany(c => c.States); 
+4

+1包括lambda擴展。 – 2009-06-17 20:55:43