如何在 Linq 中使用 group by 和 sum 获取记录
How to get record using group by and sum in Linq
我有一个table喜欢:
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
如果 table 较小(记录数较少),您可以加载所有行,然后像这样处理它们:
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();
应该这样做:
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");
我有一个table喜欢:
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
如果 table 较小(记录数较少),您可以加载所有行,然后像这样处理它们:
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();
应该这样做:
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");