c# - LINQ:分组子组

标签 c# .net linq igrouping nested-groups

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

enter image description here

这是 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的结果:

enter image description here

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

  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();

最佳答案

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

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();

关于c# - LINQ:分组子组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39081806/

相关文章:

c# - 欧拉计划 #16 - C# 2.0

c# - 以编程方式安装证书吊销列表 C#

c# - 在 C# 中,如何使用另一个列表的 StartsWith() 条件筛选列表?

c# - 我无法让分页显示在以列表为源的 GridView 的每个页面中

c# - 为什么这个 catch all block 实际上并没有 catch all

c# - 比较 JSON 结构

c# - asp.net core 2显示指定的 key 太长;最大 key 长度为 3072 字节

c# - 多线程共享局部变量

.net - <%# %> 和 <%= %> 有什么区别?

c# - Entity Framework 中的导航属性问题