2010-05-09 34 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