你如何加入LinqToSQL?

Sha*_*ica 2 c# linq join linq-to-sql

我有以下形式的数据设置:State1-> n County1-> n City.

在我的State对象中,我想返回包含至少一个人口大于的城市的所有县p.如果我在sql中写这个将是:

select distinct co.*
from County co join City ci on ci.CountyID = co.ID
where ci.Population > @p
and co.StateCode = @StateCode
Run Code Online (Sandbox Code Playgroud)

也许sql可以更好地进行优化(我肯定会感谢指针),但这不是重点......

无论如何,我想在州级的Linq做这件事.我的代码(显然没有编译)现在看起来像这样:

var q = 
  from co in Counties
  where co.Cities // uh-oh, now what?
Run Code Online (Sandbox Code Playgroud)

你怎么做呢?

Mar*_*ell 6

假设你有关联属性......

var q =  from co in Counties
         where co.Cities.Any(city =>city.Population > p)
         select co;
Run Code Online (Sandbox Code Playgroud)

或者干脆:

var q = Counties.Where(co => co.Cities.Any(city => city.Population > p));
Run Code Online (Sandbox Code Playgroud)