[LINQ Operators] GroupJoin

The “GroupJoin” operator performs a grouped join of two sequences based on matching keys.

 

1. Sample Data Object

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

 

2. “GroupJoin” operator

  • Deferred operator
  • Purpose: Join

 

3. Prototypes

public static IEnumerable GroupJoin<TOuter, TInner, TKey, TResult>(
  this IEnumerable<TOuter> outer,
  IEnumerable<TInner> inner,
  Func<TOuter, TKey> outerKeySelector,
  Func innerKeySelector,
  Func resultSelector
)

The “GroupJoin()” operator works very similarly to the “Join()” operator. “GroupJoin()” produces hierarchical results; elements from outer are paired with collections of matching elements from inner.

 

4. Example 1 (Standard Operator)

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

var empsByCity =
  cities.GroupJoin( // outer sequence
  emps, // inner sequence
  c => c.Id, // outer key
  e => e.CityId, // inner key
  (c, empGroup) => new
  {
    City = c.Name,
    EmpCount = empGroup.Count(),
    Emps = empGroup.Select(e => e.Name)
  } // result
);

foreach (var city in empsByCity)
{
  Console.WriteLine($"= City: {city.City}, {city.EmpCount} Employees =");
  foreach (var emp in city.Emps)
  {
    Console.WriteLine($"{emp}");
  }
}

 

5. Example 2 (Query Expression)

  • join / on / 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 into empGroup // keys
  select new
  {
    City = c.Name,
    EmpCount = empGroup.Count(),
    Emps = empGroup.Select(e => e.Name)
  }; // result

foreach (var city in empsByCity)
{
  Console.WriteLine($"= City: {city.City}, {city.EmpCount} Employees =");
  foreach (var emp in city.Emps)
  {
    Console.WriteLine($"{emp}");
  }
}

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