简体   繁体   中英

How to get record using group by and sum in Linq

I have a table like:

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

I want the following result:

AttendaceDate                 Attendance
November,2015                 2.00
December,2015                 1.50

This should do it:

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) }
);

During display of the data, you can convert the year and month to the text you want to show by doing:

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

If you have small table (with small number of records), you can load all rows and then process them like this:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM