[LINQ Operators] GroupBy

The “GroupBy” operator groups the elements of a sequence using the provided keyselector.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “GroupBy” operator

  • Deferred operator
  • Purpose: Grouping

 

3. Prototypes

public static IEnumerable<IGrouping<K, T>> GroupBy<T, K>
(this IEnumerable<T> source,  Func<T, K> keySelector)

The “GroupBy()” operator returns a sequence of “IGrouping<K, T>” objects.

public interface IGrouping<K, T> : IEnumerable<T>
{
  K Key { get; }
}

The prototypes of the “GroupBy()” operator look daunting. But if you look at the examples, its usages are not as difficult as they look.

 

4. Example 1 (Standard Operator)

Let’s group employers by a city.

var emps = Employee.GetEmployees();
var cities = City.GetCities();

var empsByCity = cities.Join( // outer sequence
  emps, // inner sequence
  c => c.Id, // outer key
  e => e.CityId, // inner key
  (c, e) => new { City = c.Name, Employer = e.Name } // result
);

var empsByCityGroup = empsByCity.GroupBy(e => e.City);

foreach (var group in empsByCityGroup)
{
  Console.WriteLine($"City: {group.Key} - {group.Count()} Employees");
  foreach (var e in group)
  {
    Console.WriteLine($"-- {e.Employer}");
  }
}

 

5. Example 2 (Query Expression)

  • group by into
var emps = Employee.GetEmployees();
var cities = City.GetCities();

var empsByCity = from c in cities // outer sequence
  join e in emps // inner sequence
  on c.Id equals e.CityId // keys
  select new { City = c.Name, Employer = e.Name }; // result

var empsByCityGroup = from g in empsByCity
  group g by g.City into cityGroup
  select cityGroup;

foreach (var group in empsByCityGroup)
{
  Console.WriteLine($"City: {group.Key} - {group.Count()} Employees");
  foreach (var e in group)
  {
    Console.WriteLine($"-- {e.Employer}");
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s