2013-05-28 64 views
1

我有一個簡單的LINQ查詢,該組由一個場TeamLINQ到組由2列在C#

var qbt = db.Calls.GroupBy(x => x.team).Select(call => new 
     { 
      Team = call.Key, 
      Number=call.Count() 
     }); 

將返回:

Team Number 
ta 100 
tb 98 
tc 123 

如何更改查詢有附加列「地位」,使其返回:

Team Number Status 
ta 40  Open 
ta 60  Closed 
tb 58  Open 
tb 40  Closed 
tc 1  Open 
tc 122 Closed 

我嘗試添加另一組:

var qbt = db.Calls.GroupBy(x => x.team).GroupBy(y => y.status).Select(call => new 
     { 
      Team = call.Key, 
      Status = call.Key2, 
      Number=call.Count() 
     }); 

......但那不會編譯。

謝謝你,馬克

回答

4

您需要創建內部groupping新的匿名類型,應該做的伎倆。

var qbt = db.Calls 
    .GroupBy(x => new { Team = x.team, Status = x.status }) 
    .Select(call => new 
    { 
     Team = call.Key.Team, 
     Status = call.Key.Status, 
     Number=call.Count() 
    }); 
+2

您的語法錯誤。這應該是'Team = call.Key.Team'和'Status = call.Key.Status'('Key2'不存在,並且'Key'將是groupby中創建的匿名類型) – Jamiec

+1

Right - 甚至沒有注意到這部分,因爲它是從問題複製粘貼的;儘管最重要的部分似乎沒有問題。謝謝。 – Pako

+0

非常感謝 – Mark

8

你可以在一個匿名類型組:

.GroupBy(x => new { x.team, x.status }) 

有了相應的選擇:

.Select(call => new 
    { 
     Team = call.Key.team, 
     Status = call.Key.status, 
     Number = call.Count() 
    });