开发者

LINQ query to navigate an object hierachy

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

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

public class开发者_Python百科 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?


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;


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜