LINQ:分组子组

LINQ: Grouping SubGroup

如何对子组进行分组以创建大陆列表,其中每个大陆都有自己的县,每个国家都有自己的城市,就像这样table

这是t-sql:

select Continent.ContinentName, Country.CountryName, City.CityName 
from  Continent
left join Country
on Continent.ContinentId = Country.ContinentId

left join City
on Country.CountryId = City.CountryId

和 t-sql 的结果:

我试过了,但是它以错误的方式对数据进行了分组,我需要完全按照上面的方式进行分组 table

  var Result = MyRepository.GetList<GetAllCountriesAndCities>("EXEC sp_GetAllCountriesAndCities");

    List<Continent> List = new List<Continent>();


    var GroupedCountries = (from con in Result
                             group new
                             {


                                 con.CityName,

                             }

                             by new
                             {

                                 con.ContinentName,
                                 con.CountryName
                             }

            ).ToList();

    List<Continent> List = GroupedCountries.Select(c => new Continent()
    {

        ContinentName = c.Key.ContinentName,
        Countries = c.Select(w => new Country()
        {
            CountryName = c.Key.CountryName,

            Cities = c.Select(ww => new City()
            {
                CityName = ww.CityName
            }
            ).ToList()

        }).ToList()


    }).ToList();

你应该应用分组两次

var grouped = Result
    .GroupBy(x => x.CountryName)
    .GroupBy(x => x.First().ContinentName);

var final = grouped.Select(g1 => new Continent
{
    ContinentName = g1.Key,
    Countries = g1.Select(g2 => new Country
    {
        CountryName = g2.Key,
        Cities = g2.Select(x => new City { CityName = x.CityName }).ToList()
    }).ToList()
});

您需要按大陆对所有内容进行分组,这些按国家/地区分组,然后按城市对国家/地区进行分组:

List<Continent> List = MyRepository.GetList<GetAllCountriesAndCities>("EXEC sp_GetAllCountriesAndCities")
    .GroupBy(x => x.ContinentName)
    .Select(g => new Continent 
    {
        ContinentName = g.Key,
        Countries = g.GroupBy(x => x.CountryName)
                     .Select(cg => new Country 
                     {
                         CountryName = cg.Key,
                         Cities = cg.GroupBy(x => x.CityName)
                                    .Select(cityG => new City { CityName = cityG.Key })
                                    .ToList()
                     })
                     .ToList()
    })
    .ToList();

我知道这已经过时了,但我想提一下微软的一种更简单的方法,它更具可读性。这是一个只有 2 个级别的示例,但它很可能适用于访问此页面的其他人(比如我)

 var queryNestedGroups =
        from con in continents
        group con by con.ContinentName into newGroup1
        from newGroup2 in
            (from con in newGroup1
             group con by con.CountryName)
        group newGroup2 by newGroup1.Key;

相关文档位于 https://docs.microsoft.com/en-us/dotnet/csharp/linq/create-a-nested-group 并以 Student 对象为例

我确实想提一下,他们用于打印的方法比仅仅在大陆对象上创建快速打印功能更难