LINQ查询以导航对象层次结构

时间:2010-03-18 04:12:38

标签: c# linq

假设我有一个国家/州/城市的对象图,如下所示:

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; }
}

是否有一种简单的方法可以查询List<Country>以获取所有城市?

2 个答案:

答案 0 :(得分:3)

countryList.SelectMany(c => c.States).SelectMany(s => s.Cities)怎么样?

或许这个?

var cities = from country in countryList
             from state in country.States
             from city in state.Cities
             select city;

答案 1 :(得分:1)

不能简单! : - )

var cities = from country in countries //List<Country>
             from state in country.States
             from city in state.Cities
             select city.Name;