LINQ:分组子组

时间:2016-08-22 14:12:39

标签: c# .net linq igrouping nested-groups

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

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

3 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

您应该应用分组两次

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

答案 2 :(得分:0)

我知道这很老了,但是我想提一下每个Microsoft更简单的方法,它更具可读性。虽然这是一个只有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 并以学生对象为例

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