LINQ Aggregate Queries: Multiple Group By Columns

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 g

You 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!


Follow

Get every new post delivered to your Inbox.