开发者

LINQ Query with 3 levels

开发者 https://www.devze.com 2022-12-29 12:53 出处:网络
I have a business object structured like this: Country has States, State has Cities So Country[2].States[7].Cities[5开发者_Python百科].Name would be New York

I have a business object structured like this:

Country has States, State has Cities

So Country[2].States[7].Cities[5开发者_Python百科].Name would be New York

Ok, I need to get a list of all the Country objects which have at least 1 City.IsNice == true

How do I get that?


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

Another option :

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();


I would do it in one of two ways:

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

or

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


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

精彩评论

暂无评论...
验证码 换一张
取 消