我有三节课;州,县和市。州包含县名单。县包含城市列表。
public class State
{
public string StateCode;
List<County> Counties;
List<string> CitiesInState
{
get
{
return //LINQ STATEMENT TO GET LIST OF ALL CITYNAMES FROM LIST OF COUNTIES
}
}
}
public class County
{
public string CountyName;
List<City> Cities;
}
public class City
{
public string CityName;
}
我正在尝试返回州内所有CityNames的列表。由于这是List中的项目的属性,List是另一个List中的项目,我不确定它是否可行。我无法编写任何甚至可以编译的内容。这可能吗?有人能指出我正确的方向吗?
答案 0 :(得分:4)
您正在询问如何展平嵌套列表:
Counties.SelectMany(c => c.Cities).Select(c => c.CityName)
答案 1 :(得分:3)
听起来你只需要:
return Counties.SelectMany(county => county.Cities) // IEnumerable<City>
.Select(city => city.CityName) // IEnumerable<string>
.ToList(); // List<string>
SelectMany
(最简单的形式)可以看作是一个“扁平化”操作 - 原始集合的每个元素都被投射到另一个集合中,并且所有这些“子集合”的所有元素都被生成反过来。
有关详细信息,请参阅我的Edulinq article on SelectMany
,以及有关其他重载的信息。 (其他一个重载可用于在SelectMany
内提供“城市名称”投影,但我发现这种方法更具可读性。)