Codectionary / Developer documentation / C#

Keep Parent Rows with GroupJoin

Associate each outer value with its matching inner sequence, including empty groups.

Read the syntax

Associate each outer value with its matching inner sequence, including empty groups.

The PHP group contains two lessons and the C# group is empty.

What it is and why to use it

A course summary often needs to show courses with no lessons as well as populated courses. GroupJoin produces one result per outer element and gives its result selector the matching inner sequence. An unmatched outer element receives an empty sequence, which can be counted or displayed deliberately.

How it works

The key selectors identify related outer and inner records. The result selector receives the outer record and an IEnumerable of its matches. GroupJoin is deferred in LINQ to Objects and can build an inner lookup. Combining grouping with DefaultIfEmpty and flattening can express outer-join behaviour, but the grouped result itself is not a flat row for every match.

Common mistakes and limitations

Do not expect the grouped parameter to be one record or null. Do not assume all parents have matches. Avoid repeated expensive work inside a selector and remember that IQueryable providers may have different supported translations from in-memory LINQ.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

parents.GroupJoin(children, p => p.Id, c => c.ParentId, (p, matches) => result)

Examples

Count lessons for every course

Include a course whose matching group is empty.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var courses = new[] { (Id: 1, Name: "PHP"), (Id: 2, Name: "C#") };
var lessons = new[] { (CourseId: 1, Title: "Arrays"), (CourseId: 1, Title: "Classes") };
var lines = courses.GroupJoin(lessons, c => c.Id, l => l.CourseId,
    (course, matches) => $"{course.Name}: {matches.Count()}");
foreach (var line in lines) Console.WriteLine(line);
  1. Each course reaches the result selector once.
  2. The PHP group contains two lessons and the C# group is empty.
  3. Count returns zero for the empty group, so the summary retains both parents.
  4. Expected output: PHP: 2 C#: 0
  5. Use grouped matches when the result is naturally one row per parent.

Display a deliberate empty-group label

Join matching titles for a parent or supply a fallback value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var courses = new[] { (Id: 1, Name: "PHP"), (Id: 2, Name: "C#") };
var lessons = new[] { (CourseId: 1, Title: "Arrays") };
var lines = courses.GroupJoin(lessons, c => c.Id, l => l.CourseId,
    (course, matches) => course.Name + ": " + string.Join(", ", matches.Select(x => x.Title).DefaultIfEmpty("(none)")));
foreach (var line in lines) Console.WriteLine(line);
  1. The matching group is projected to title strings.
  2. DefaultIfEmpty contributes the placeholder only when that sequence is empty.
  3. string.Join creates one display line per course rather than flattening the entire result into matched pairs.
  4. Expected output: PHP: Arrays C#: (none)
  5. Use grouped matches when the result is naturally one row per parent.

Best practices

  • Use grouped matches when the result is naturally one row per parent.
  • Make the empty-group display policy explicit.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading