2

Let's say I have an object graph of Countries / States / Cities, like below:

public class City
{
    public string Name { get; set; }
}

public class State
{
    public List<City> Cities { get; set; }
}

public class Country
{
    public List<State> States { get; set; }
}

Is there a simple way to query a List<Country> to get all the cities?

2 Answers2

3

How about countryList.SelectMany(c => c.States).SelectMany(s => s.Cities)?

Or maybe this?

var cities = from country in countryList
             from state in country.States
             from city in state.Cities
             select city;
Gabe
  • 84,912
  • 12
  • 139
  • 238
1

Can't be simpler! :-)

var cities = from country in countries //List<Country>
             from state in country.States
             from city in state.Cities
             select city.Name;
Enigmativity
  • 113,464
  • 11
  • 89
  • 172