LINQ:分组子组

Luc*_*ucy 4 .net c# linq igrouping nested-groups

如何将SubGroup分组以创建大陆列表,其中每个大陆都有自己的县,每个国家/地区都有自己的城市,如此表

在此输入图像描述

这是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
Run Code Online (Sandbox Code Playgroud)

和t-sql的结果:

在此输入图像描述

我尝试了这个,但它以错误的方式对数据进行分组,我需要像上表一样进行分组

  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();
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 9

您需要按大陆划分所有内容,按国家划分,按国家/地区划分:

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();
Run Code Online (Sandbox Code Playgroud)