typestar

GroupJoin in C#

The left join's cousin: every left row, with its group of matches.

var authors = new[] { (Id: 1, Name: "Ada"), (Id: 2, Name: "Alan") };
var papers = new[]
{
    (AuthorId: 1, Title: "Notes"), (AuthorId: 1, Title: "Sketch"),
};

// GroupJoin keeps every left row with its group of matches, even empty
var report = authors.GroupJoin(papers,
    a => a.Id, p => p.AuthorId,
    (a, ps) => $"{a.Name}: {ps.Count()} papers");
Console.WriteLine(string.Join("\n", report));

How it works

  1. GroupJoin pairs each author with a sequence of their papers.
  2. An author with no papers still appears, with an empty group.
  3. ps.Count() collapses each group to a number.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
387
Tokens
102
Three-star pace
85 tpm

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

Type this snippet

Step 2 of 3 in Joins & lookups, step 8 of 17 in LINQ in depth.

← Previous Next →