2014-01-23 50 views
9

我有一個包含如下數據的多行數據集數據庫表中的多個列組如何使用LINQ

ItemId    Code        StatusId 
-------------------- --------------------------------------------- 
62224    NC0860000        8 
62225    NC0860000        8 
62226    NC0860000        8 
62227    NC0860200        5 
62228    NC0860000        5 
62229    NC0860000        5 
62230    NC0860000        5 

我想做到的是輸出結果作爲

NC0860000 8 3 (code, status, count) 
NC0860000 5 3 

我不完全瞭解如何在EF中進行分組。我能拿到鑰匙,並使用查詢作爲一個組的計數:

var results = (from ssi in ctx.StageSubmitItems 
          join s in ctx.StageSubmissions on ssi.SubmissionId equals s.SubmissionId 
          where s.ContributorCode == contributorId 
          group ssi.SubmitItemId by ssi.AgencyCode into g 
          select new {AgencyCode = g.Key, Count = g.Count() }).ToList(); 

但我無法通過代碼弄清楚如何分組,然後由StatusId,然後產生總數的計數行狀態。

我很感激任何有關如何完成此操作或我在查詢中執行的操作不正確的建議。

在此先感謝

-Cheers

回答

22

您可以通過一個新的匿名類組,如下所示:

// I created a Foo class to show this working 
var fooList = new List<Foo> { 
    new Foo { ItemId = 62224, Code = "NC0860000", StatusId = 8 }, 
    new Foo { ItemId = 62225, Code = "NC0860000", StatusId = 8 }, 
    new Foo { ItemId = 62226, Code = "NC0860000", StatusId = 8 }, 
    new Foo { ItemId = 62227, Code = "NC0860200", StatusId = 5 }, 
    new Foo { ItemId = 62228, Code = "NC0860000", StatusId = 5 }, 
    new Foo { ItemId = 62229, Code = "NC0860000", StatusId = 5 }, 
    new Foo { ItemId = 62230, Code = "NC0860000", StatusId = 5 }, 
}; 

var results = (from ssi in fooList 
    // here I choose each field I want to group by 
    group ssi by new { ssi.Code, ssi.StatusId } into g 
    select new { AgencyCode = g.Key.Code, Status = g.Key.StatusId, Count = g.Count() } 
).ToList(); 

// LINQPad output command 
results.Dump(); 

提供的數據顯示,這裏是輸出:

AgencyCode Status Count 
NC0860000 8  3 
NC0860200 5  1 
NC0860000 5  3 

我猜「NC0860200」是一個錯誤,但它在你的樣本數據,所以我包括它。