我有一個業務對象的結構是這樣的:LINQ查詢與3級
國家有美國,國家有城市
所以Country[2].States[7].Cities[5].Name
將New York
好吧,我需要得到列表所有至少有1個國家/地區對象City.IsNice == true
我該如何獲得?
我有一個業務對象的結構是這樣的:LINQ查詢與3級
國家有美國,國家有城市
所以Country[2].States[7].Cities[5].Name
將New York
好吧,我需要得到列表所有至少有1個國家/地區對象City.IsNice == true
我該如何獲得?
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));
var result = (from country in db.Countries
from state in country.States
from city in state.Cities
where city.IsNice
select county).Distinct();
我會做它的兩種方法之一:
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);
你的第二個不是LINQ它只是使用相同的擴展方法作爲LINQ使用 – 2010-05-09 17:43:09
@Rune FS:LINQ,而不是LINK;) – abatishchev 2010-05-09 17:46:01
@abatishchev至少我得到了第二個權利:)(thx) – 2010-05-09 17:48:29
var result = Countries
.SelectMany(a => a.States)
.SelectMany(b => b.Cities)
.Where(b => b.IsNice == true)
.ToList();
這個回報城市,而不是國家 – 2010-05-09 17:53:59
這給了城市而不是國家。 – brickner 2010-05-09 17:33:14
@brickner:匆匆了一下;) – abatishchev 2010-05-09 17:43:31
這個查詢返回*每個*美國城市的國家......例如,如果你在一個國家有10個不錯的城市,這個查詢將返回相同的國家10次 – 2010-05-09 17:52:48