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

Thursday, 8 November 2012

Application level error handling

On the project I've been working on, we've been asked to log any exceptions that are thrown by the site. There are packages out there (like ELMAH), but in case you want to add some form of custom logging (or extra handling), there's a useful chunk of sample code for doing just that. :)