Logo
  • Home
  • Services
  • Articles
    • Local Notion

      Own your data with Local Notion

      →

    • BlockchainSQL Server

      Access Bitcoin as an SQL Database

      →

    • Auto Mouse

      Use your mouse pain-free

      →

    • 🌗

      Lumina

      Your display. Your way.

      →
    • Our Tech
    • Case Studies
    • Contact Us

Join related collections and preserve unmatched rows in LINQ

  1. Articles
  2. Coding
  3. .NET
  4. Join related collections and preserve unmatched rows in LINQ

An inner join keeps matching pairs. A left join also keeps each left-side item that has no match, supplying a missing right-side value.

The query syntax pattern below works across older and current C# versions. The essential step is DefaultIfEmpty. Flattening a group without it loses unmatched rows.

Run the left join

In a .NET console project's Program.cs, run:

C#
var owners = new[] { new Owner(1, "Ada"), new Owner(2, "Lin") };
var notes = new[] { new Note(1, "Draft") };
var query = from owner in owners
			join note in notes on owner.Id equals note.OwnerId into matches
			from note in matches.DefaultIfEmpty()
			select $"{owner.Name}: {note?.Title ?? "(none)"}";
foreach (string line in query) Console.WriteLine(line);

public sealed record Owner(int Id, string Name);
public sealed record Note(int OwnerId, string Title);

The output is Ada: Draft followed by Lin: (none). Add a second matching note and Ada produces two result rows, one for each match.

Extend the relation carefully

Add another join using the appropriate keys when a third collection is required. The syntax's left key refers to the outer range variable and its right key to the newly joined variable. It is not a rule about a database's parent/child naming.

A filter on the right-side item after a left join can remove the unmatched rows. Put the intended filter on the right-hand source before joining, or explicitly retain the missing case. For EF Core, confirm the provider translates the chosen expression. LINQ-to-Objects behavior does not prove database query support.

Official references

Join Operations - C#
A join of two data sources associates objects with objects that share an attribute across data sources. Learn about join methods in the LINQ framework in C#.
https://learn.microsoft.com/en-us/dotnet/csharp/linq/standard-query-operators/join-operations
LINQ join operations

Author: Herman Schoenfeld

COMPANY

Our Process

Case Studies

Our Technology

Contact Us

SERVICES

AI Engineering

Blockchain/Web3

Desktop Software Dev

App Development

Web Development

Enterprise Systems

IT Services

Consulting

PRODUCTS

BlockchainSQL Server

Local Notion

Notion CMS

Auto Mouse

LEGAL

Website Terms of Use

Privacy Policy (GDPR)