2009-06-17 94 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