如何在Linq中使用group by和sum获取记录

时间:2015-12-23 12:54:09

标签: c# entity-framework linq linq-to-entities

我有一张表:

AttendaceDate                 Attendance
2015-12-05 00:00:00.000       1.00
2015-12-01 00:00:00.000       0.50
2015-11-01 00:00:00.000       1.00
2015-12-01 00:00:00.000       1.00

我想要以下结果:

AttendaceDate                 Attendance
November,2015                 2.00
December,2015                 1.50

2 个答案:

答案 0 :(得分:1)

这应该这样做:

var grouped = (
    from s in context.Table
    group s by new { s.AttendanceDate.Year, s.AttendanceDate.Month } into g
    select new { Year = g.Key.Year, Month = g.Key.Month, Attendance = g.Sum(s => s.Attendance) }
);

在显示数据期间,您可以通过执行以下操作将年份和月份转换为您要显示的文本:

new DateTime(g.Year, g.Month, 1).ToString("MMMM,yyyy");

答案 1 :(得分:0)

如果你有一个小表(记录数量很少),你可以加载所有行,然后像这样处理它们:

var res = dbContext.YouTable.ToList()
    .GroupBy(x => new { x.AttendaceDate.Year, x.AttendaceDate.Month })
    .Select(x => new { x.Key.Year, Month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x.Key.Month), Sum = x.Sum(y => y.Attendance)}).ToList();