2010-05-09 36 views
5

我有一个业务对象的结构是这样的:LINQ查询与3级

国家有美国,国家有城市

所以Country[2].States[7].Cities[5].NameNew York

好吧,我需要得到列表所有至少有1个国家/地区对象City.IsNice == true

我该如何获得?

回答

3
var selectedCountries = 
    countries.Where(
     co => co.States.Any(
      s => s.Cities.Any(
       ci => ci.IsNice))); 

另一种选择:

var selectedCountries = 
    countries.Where(
     co => co.States.SelectMany(s => s.Cities).Any(
      ci => ci.IsNice)); 
1
var result = (from country in db.Countries 
      from state in country.States 
      from city in state.Cities 
      where city.IsNice 
      select county).Distinct(); 
+0

这给了城市而不是国家。 – brickner 2010-05-09 17:33:14

+0

@brickner:匆匆了一下;) – abatishchev 2010-05-09 17:43:31

+0

这个查询返回*每个*美国城市的国家......例如,如果你在一个国家有10个不错的城市,这个查询将返回相同的国家10次 – 2010-05-09 17:52:48

0

我会做它的两种方法之一:

var selectedCountries = from country in countries 
         from state in country.States 
         from city in state.Cities 
         where city.IsNice 
         select country; 

var selectedCountries = 
    countries.Where(country => 
        country.States.FirstOrDefault(state => 
                state.Cities.FirstOrDefault(city => 
                       city.IsNice) != null) != null); 
+0

你的第二个不是LINQ它只是使用相同的扩展方法作为LINQ使用 – 2010-05-09 17:43:09

+0

@Rune FS:LINQ,而不是LINK;) – abatishchev 2010-05-09 17:46:01

+0

@abatishchev至少我得到了第二个权利:)(thx) – 2010-05-09 17:48:29

0
var result = Countries 
    .SelectMany(a => a.States) 
    .SelectMany(b => b.Cities) 
    .Where(b => b.IsNice == true) 
    .ToList(); 
+0

这个回报城市,而不是国家 – 2010-05-09 17:53:59