Monday, 12 November 2012

LINQ, Counts and Group By

After a particularly busy weekend full of late nights working remotely towards a looming deadline, I was having trouble with writing a LINQ query that would return me values based on a GROUP BY clause. What I basically wanted was:

SELECT COUNT(Id)
FROM Table
GROUP BY UserId

I had no idea what the LINQ GroupBy() method actually returned, but this article helped me figure it out.

Table
  .GroupBy(x => x.UserId)
  .Select(g => g.Count());

Or, even more handy:

Table
  .GroupBy(x => x.UserId)
  .Select(g => new { userId = g.Key, count = g.Count() });

No comments:

Post a Comment