Thursday, August 15, 2013

A groupby example in Linq

This is an example of applying a group by on a Name object. I started off grouping by just first name, and decided to add Age and do a group by using multiple fields.

class Name {
 public string FirstName;
 public string LastName;
 public int Age;
void Main()
 var names = new List{ new Name{ FirstName="Joe", LastName="A", Age=11}, new Name{ FirstName="Joe", LastName="B", Age=11}
  , new Name{ FirstName="Timmy", LastName="Pumpurdink"}, new Name{ FirstName="Timmy", LastName="Doheenee"},  new Name{ FirstName="Timmy", LastName="Doheenee", Age=1}
  var grouped = names.GroupBy (n => new {n.FirstName, n.Age}).Select (n => new {Key=n.Key, Count=n.Count(), LastNames=string.Join(", ", n.AsEnumerable().OrderBy (x => x.LastName).Select (x => x.LastName).ToList())}).Dump();

Here's the result:

No comments: