2016-08-22 63 views
3

自己的城市,如該表LINQ:分組亞組

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

它以錯誤的方式分組?它以何種方式錯誤? –

+0

我甚至沒有在T-SQL中看到一個組。 – juharr

+0

我想你必須在第一組的投影中重新組合:'Result.GroupBy(x => x.ContinentName).Select(g => g.GroupBy(x => x.CountryName))''。 –

回答

4

您可以通過大陸需要小組的一切,這些按國家和按城市劃分的國家:

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

謝謝蒂姆!你總是幫我做我的好朋友!這正是我期待的。你怎麼看待Linq的這種分組方式,這很好,還是我應該在sql server而不是Linq中進行分組? 我的另一個問題是:我是一個新的開發人員你對我的建議是什麼,才能成爲真正的專業開發人員:)? – Lucy

+0

我花了兩天的時間尋找如何在sql server中進行分組,但是找不到任何有用的文章 – Lucy

+0

即使你在數據庫中分組,你也不會得到你的嵌套結構,所以你現在的方法很好。另一種方法是按大陸,國家和城市對數據庫中的結果集進行排序。然後,一個簡單而高效的循環就足以創建你的列表。 –

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

它的工作,非常感謝你:))但是我不明白var分組= =結果 .GroupBy(x => x.CountryName ) .GroupBy(x => x.First()。ContinentName); 你能告訴我一個更簡單的方法來分組嗎?像我在我的代碼中使用的東西...謝謝你 – Lucy