Sunday, November 20, 2011

Grouping with linq in C#

Nice clear post on grouping with linq in C# (and VB.NET too) by Christian Nagel:
http://weblogs.thinktecture.com/cnagel/2010/10/linq-grouping-with-c-and-visual-basic.html

Lambda syntax: 



var q = Formula1.GetChampions()
.GroupBy(r => r.Country)
.Select(g => new
{
Count = g.Count(),
Group = g
})
.OrderByDescending(x => x.Count)
.ThenBy(x => x.Group.Key)
.Select(x => new
{
Country = x.Group.Key,
Count = x.Count,
Racers = x.Group.Select(r => r.FirstName + " " + r.LastName)
})
.Take(5);


Similarly in comprehension syntax: 

var q = (from r in Formula1.GetChampions()
                     group r by r.Country into g
                     let count = g.Count()
                     orderby count descending, g.Key
                     select new
                     {
                         Country = g.Key,
                         Count = count,
                         Racers = from r1 in g
                                  select r1.FirstName + " " + r1.LastName
                     }).Take(5);