2010-03-18 70 views
2

比方說,我有國家/國家/城市的對象圖,如下圖所示: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>讓所有的城市?

+0

退房http://stackoverflow.com/questions/1590723/ ... SelectMany()方法將爲你做。 – 2010-03-18 04:16:49

+0

或搜索SO「selectmany」或「flatten linq」。 – 2010-03-18 04:17:10

+0

好的..我的q是一個重複:http://stackoverflow.com/questions/1938409/linq-how-to-convert-the-nested-hierarchical-object-to-flatten-object 我很高興爲此被關閉..什麼是協議,我只是刪除它? – TesterTurnedDeveloper 2010-03-18 04:19:57

回答

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

不能簡單! :-)

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