LINQ Aggregate Queries: Multiple Group By Columns
November 12, 2009 4 Comments
I recently had the need to SUM a column grouped by two other columns. Here’s the view:
SELECT SolutionID, EventName, EventDuration FROM Events
I needed this:
SELECT SolutionID, EventName, SUM(EventDuration) EventTotal FROM Events GROUP BY SolutionID, EventName
Here’s the LINQ:
var events = from e in summary
group e by new { e.SolutionID, e.EventDetail } into g
let TotalMinutes = g.Sum(x => x.EventDuration)
orderby TotalMinutes descending
select new EventSummary
{
SolutionID = g.Key.SolutionID,
Name = g.Key.EventDetail,
Seconds = TotalMinutes,
Minutes = TotalMinutes / 60.0,
Hours = (TotalMinutes / 60.0) / 60.0
};
The magic is in line 2:
group e by new { e.SolutionID, e.EventDetail } into gYou can group by as many columns as you need with that little nugget. Using the anonymous type feature in C# 3.0 you can group on as many columns as you need. Enjoy!
Advertisement
Thanks a lot. it really helped me lot
Cheers,
Glad I could help!
Thanks man, you save my time
Thanks Dave. Very clear and simple. This helped me. This is the end of my search on how to group by on multiple columns.