Group By with LINQ
Today I wanted to do a group-by query with LINQ which is something I did before. It turned out to be kind of easy.
If you just want to group by a single field.
(from s in db.CrewStatsSet
where s.LogDate >= date1 && s.LogDate <= date2 && s.Action == action
group s by s.User.nick into g
orderby g.Count() descending
select new CrewStatsData
{
Nick = g.Key,
Count = g.Count(),
}).ToList();
And if you need to group by multiple fields.
(from s in db.CrewStatsSet
where s.LogDate >= date1 && s.LogDate <= date2 && s.Action == action
group s by new { s.User.nick, s.Action, s.User.userID } into g
orderby g.Count() descending
select new CrewStatsData
{
Nick = g.Key.nick,
Count = g.Count(),
ActionId = g.Key.Action,
UserId = g.Key.userID
}).ToList();