Thursday, 12 July 2012

C# LINQ GroupBy example

public void TestGroupBy()
{
  var people = new[]
  {
    new { Name="John", City="London", Side="South", Age=20},
    new { Name="John", City="London", Side="North", Age=55},
    new { Name="Eli", City="London", Side="North", Age=39},
    new { Name="Anna", City="NY", Side="North", Age=23},
    new { Name="Marc", City="NY", Side="South", Age=51},
    new { Name="Julie", City="NY", Side="South", Age=67},
  }.ToList();
 
  var ageByCitySide = people
      .GroupBy(p => new {p.City, p.Side})
      .Select(r => new {r.Key.City, r.Key.Side, AverageAge = r.Average(p => p.Age)})
      .OrderBy(p=>p.AverageAge);
 
  foreach (var p in ageByCitySide)
  {
    Console.WriteLine("{0},{1} AvgAge:{2}",p.City,p.Side,p.AverageAge);
  }
 
  var youngOldByCitySide = people
      .GroupBy(p => new { p.City, p.Side }, r => new { r.Age, YoungOld = (r.Age > 50 ? "old" : "young")})
      .Select(r => new { r.Key.City, r.Key.Side, NoOfYoung=r.Count(p=>p.YoungOld =="young"), NoOfOld=r.Count(p=>p.YoungOld =="old"), AverageAge = r.Average(p => p.Age) })
      .OrderBy(p => p.AverageAge);
 
  foreach (var p in youngOldByCitySide)
  {
    Console.WriteLine("{0},{1} AvgAge:{2}, YoungPpl:{3}, OldPpl:{4}", p.City, p.Side, p.AverageAge, p.NoOfYoung, p.NoOfOld);
  }
}

No comments:

Post a Comment