Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query with 3 levels

Tags:

linq

I have a business object structured like this:

Country has States, State has Cities

So Country[2].States[7].Cities[5].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?

like image 308
Ian Vink Avatar asked Oct 14 '22 06:10

Ian Vink


1 Answers

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));
like image 59
Thomas Levesque Avatar answered Nov 15 '22 09:11

Thomas Levesque