为此,您需要Counties with their zero or more Cities 的概念。完成后,您可以按城市数量对县进行排序,然后按县对城市进行排序。
结果:排序的县(按城市数量降序排列),每个城市按名称排序
如果您想将其扁平化为 [County, City, IsCapital] 的组合,您可以使用 SelectMany 来执行此操作。
首先,您必须按同一县对所有项目进行分组。唉,你忘了给你的 [County, City, IsCapital] 一个类名,所以我给它起个名字GeographicalItem
IEnumerable<GeographicalItem> inputData = ...
将Counties with their Cities 分组:
var result = inputData.GroupBy(geographicalItem => geographicalItem.County,
// parameter resultSelector: for every Country, with all geograhpicalItems in this
// country make one "Country with its cities"
(country, geographicalItemsInThisCountry) => new
{
Country = country,
Cities = geoghraphicalItemsInThisCountry.Select(geographicalItem => new
{
Name = geographicalItem.City,
IsCapital = geograhpicalItem.IsCapital,
})
.OrderBy(city => city.Name)
.ToList(),
})
结果:国家序列,每个国家都有该国家的城市列表,按名称排序。每个城市都有一个名称和一个属性 IsCapital。
现在排序国家:城市最多的国家:
继续 LINQ:
.OrderByDescending(country => country.Cities.Count)
结果:排序后的国家/地区,每个国家/地区都有其排序后的城市。城市最多的国家优先。按名称排序的国家/地区内的城市。
如果你想展平结果:使用 SelectMany:
.SelectMany(county => country.Cities,
// parameter resultSelector: from every [country, city] combination make one new:
(country, city) => new
{
Country = country,
City = city.Name,
IsCapital = city.IsCapital,
});