Friday, 16 January 2009

Linq to Sql - Grouping by multiple columns

Here's an example of how to group by multiple fields in Linq to sql. The sql:

SELECT City, JobTitle, Count(1)
FROM Customer
GROUP BY City, JobTitle

Is represented by the following Linq code:

from c in DataContext.Customers
group c.JobTitle by
new
{
c.City,
c.JobTitle,
}
into g
select new
{
g.Key.City,
g.Key.JobTitle,
Total = g.Count()
}

Note that this will return an anonymous type with 3 properties City,JobTitle and Total. You could just write "select g" instead of "select new..." and then access the properties from g rather than creating this anonymous type. The example I've used can be set to a datasource and then the DataField properties can easily be set.

No comments: