Linq to Entities Group By&Sum

Phi*_*ray 1 .net linq vb.net silverlight linq-to-entities

我有以下Linq查询返回数据,但我需要聚合列在Period和Sum the Count列上.

我该怎么做呢?

LINQ

from t In tblTimes
    join h In tblEngineeringDashboard_CADMachinesCounts on t.ID Equals h.TimeID
                   Order By t.Period
                   Group By t.Period, h.Count Into Group
                   select Period, Count
Run Code Online (Sandbox Code Playgroud)

数据

Period                  Count?? 
01/01/2010 00:00:00     0
01/01/2010 00:00:00     1
01/01/2010 00:00:00     2
01/01/2010 00:00:00     3
01/01/2010 00:00:00     5
01/01/2010 00:00:00     6
01/01/2010 00:00:00     7
01/01/2010 00:00:00     9
01/01/2010 00:00:00     11
01/01/2010 00:00:00     12
01/01/2010 00:00:00     14
01/01/2010 00:00:00     15
01/01/2010 00:00:00     17
01/01/2010 00:00:00     21
01/01/2010 00:00:00     22
01/01/2010 00:00:00     30
01/01/2010 00:00:00     31
01/01/2010 00:00:00     34
01/02/2010 00:00:00     0
01/02/2010 00:00:00     1
01/02/2010 00:00:00     2
01/02/2010 00:00:00     3
01/02/2010 00:00:00     5
01/02/2010 00:00:00     6
01/02/2010 00:00:00     7
01/02/2010 00:00:00     9
01/02/2010 00:00:00     12
01/02/2010 00:00:00     14
01/02/2010 00:00:00     15
01/02/2010 00:00:00     17
01/02/2010 00:00:00     21
01/02/2010 00:00:00     23
01/02/2010 00:00:00     30
01/02/2010 00:00:00     34
Run Code Online (Sandbox Code Playgroud)

等等

Bri*_*ott 5

假设您已将数据库中的记录检索到名为"PeriodRecords"的可枚举变量中,则可以使用以下Linq语句来获取各个句点以及每个句点的计数总和.

 var countsPerPeriod =
      from row in PeriodRecords      
      group row by row.Period into g
      select new {Period = g.Key, TotalPeriodCount = g.Group.Sum(row => row.Count)};
Run Code Online (Sandbox Code Playgroud)

然后,您可以按如下方式迭代新的"countsPerPeriod"变量;

foreach(var periodCount in countsPerPeriod) {
    var period = periodCount.Period;
    var count  = periodCount.TotalPeriodCount;
}
Run Code Online (Sandbox Code Playgroud)

  • 你的答案是正确但不正确的.删除".Group"所以它只是`TotalPeriodCount = g.Sum(row => row.Count)` (2认同)