2011-11-25 75 views
4

如何使用linq投影按多列進行分組?如何.GroupBy多列LINQ/Projection?

事情是這樣的:

var q = db.Areas.GroupBy(x => x.AreaCatId, x.AreaCatName, x.AreaId, x.AreaName); 

在平坦的結果得到的設置,如:

AreaCatId, AreaCatName, AreaId, AreaName 
0   US   1  FL 
0   US   2  NY 
1   Canada  3  BC 

回答

5

可以GROUPBY匿名類型:

var q = db.Areas.GroupBy(
      x => new 
       { 
        CatId = x.AreaCatId, 
        CatName = x.AreaCatName, 
        Id = x.AreaId, 
        Name = x.AreaName 
       }); 
+0

我如何排序「名稱「在GroupBy之後?我試過GroupBy(...)。OrderBy(...),但似乎沒有工作。謝謝! – JaJ

+0

@Jaj GroupBy返回一個IGrouping。如果你想扁平它,你可以使用:'.GroupBy(..)。Select(g => g.Key).OrderBy(item => item.Name);' –

+0

好吧,很酷。裏德,再次感謝! – JaJ