typestar

Join in C#

The inner join, matching rows across two sequences on a key.

var people = new[] { (Id: 1, Name: "Ada"), (Id: 2, Name: "Alan") };
var loans = new[]
{
    (PersonId: 1, Book: "Analytical Engine Sketch"),
    (PersonId: 2, Book: "On Computable Numbers"),
    (PersonId: 1, Book: "Flowcharts, Annotated"),
};

// Join matches rows on a key, like SQL's inner join
var lines = people.Join(loans,
    p => p.Id, l => l.PersonId,
    (p, l) => $"{p.Name} borrowed {l.Book}");
Console.WriteLine(string.Join("\n", lines));

How it works

  1. Key selectors name what to match: p.Id against l.PersonId.
  2. The result selector builds one output per matched pair.
  3. Rows without a partner simply do not appear.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
431
Tokens
112
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 1 of 3 in Joins & lookups, step 7 of 17 in LINQ in depth.

← Previous Next →