CodeBlanks Logo Icon CodeBlanks

Join

C# course · Advanced · Lesson 26/83

Learn to join two collections by key with Join.

Joining with Join

Join merges two sequences by a key, yielding only matching pairs (an inner join). It takes four parameters: the outer sequence, the inner sequence, the outer key selector, the inner key selector and the result selector.

Example: people.Join(cities, p => p.CityId, c => c.Id, (p, c) => ...). Each person arrives paired with the city whose Id matches. Items without a match do not appear in the result.

Inner join behavior

Join performs an inner join: only items with a match in both sequences appear in the result. Unmatched items are silently dropped.

The result order follows the outer sequence; for each outer item, matching inner items arrive in inner-sequence order. On large sequences Join builds a hash table and runs in O(n+m) time.

Exercise Join people with cities

Join the people and cities lists below on CityId/Id using Join. For each person print person name - city name with Console.WriteLine.

Show example solution
Merge with people.Join(cities, p => p.CityId, c => c.Id, (p, c) => p.Name + " - " + c.Name); then iterate the result with foreach.
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Person
{
    public string Name { get; set; }
    public int CityId { get; set; }
}

class City
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Ayşe", CityId = 1 },
            new Person { Name = "Ali", CityId = 2 }
        };
        var cities = new List<City>
        {
            new City { Id = 1, Name = "Istanbul" },
            new City { Id = 2, Name = "Ankara" }
        };
        var result = people.Join(cities, p => p.CityId, c => c.Id, (p, c) => p.Name + " - " + c.Name);
        foreach (var r in result)
        {
            Console.WriteLine(r);
        }
    }
}

Test yourself

  1. Complete the Join call

    var result = people.____(cities, p => p.CityId, c => c.Id, (p, c) => p.Name);
    Show answer
    var result = people.Join(cities, p => p.CityId, c => c.Id, (p, c) => p.Name);
  2. What does Join produce?

    • Only the outer sequence
    • Matching pairs
    • All outer and inner items
    • Groups
    Show answer

    Matching pairs — Correct. Join yields only matching pairs (inner join).

  3. Match the parameter to its role

    Outer seq
    Left source
    Inner seq
    Right source
    Outer key
    Key of outer item
    Result selector
    What to produce from a pair

All lessons in Advanced