[LINQ Operators] Join

The “Join” operator performs an inner 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. “Join” operator

  • Deferred operator
  • Purpose: Join

 

3. Prototypes

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

The “Join()” operator is quite complex. It requires 2 sequences and 2 keys (one per each sequence). In relational database terms, the “Join()” operator implements an “inner equijoin“.

 

4. Example 1 (Standard Operator)

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
);

foreach (var e in empsByCity)
{
  Console.WriteLine($"{e.City}: {e.Employer}");
}

 

5. Example 2 (Query Expression)

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

foreach (var e in empsByCity)
{
  Console.WriteLine($"{e.City}: {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