Joins and set operators
Joins and set operators
Join connects elements from two sequences using matching keys. Set operators instead answer questions about distinct values shared by or unique to sequences. Both depend on equality, but a join can produce repeated matches while set operators remove duplicates.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Match related objects
Join accepts an outer sequence, inner sequence, one key selector for each and a result selector. Each matching pair produces a result. An order without a matching customer is omitted by this inner join. A key need not be unique, so duplicates on either side can multiply results.
using System;using System.Linq;var orders = new[] { (Id: 10, Customer: 1), (Id: 11, Customer: 2), (Id: 12, Customer: 9) };var customers = new[] { (Id: 1, Name: "Ada"), (Id: 2, Name: "Bo") };var rows = orders.Join(customers, o => o.Customer, c => c.Id, (o,c) => (o.Id,c.Name)).OrderBy(r => r.Id);foreach (var row in rows) Console.WriteLine($"{row.Id}: {row.Name}");Order 12 has no matching customer and does not appear. Sorting by order ID makes output order explicit.
Expected output (reasoned, not executed):
10: Ada11: BoPreserve outer items with grouped matches
GroupJoin produces one result for each outer item, passing its sequence of matching inner items to the result selector. That sequence may be empty. It is useful for reports that include customers with no orders. Query syntax uses join ... equals ... into for a group join. On .NET 10, Enumerable.LeftJoin and RightJoin also produce flat outer-join results: every element on the preserved side appears, with one result per matching pair or one result with a default missing counterpart. A missing reference-type counterpart is null; a nonnullable value type uses its default, so project a reference or nullable representation when absence must be distinguished from a real default. For older targets, GroupJoin followed by SelectMany and DefaultIfEmpty can express a left outer join.
using System;using System.Linq;var customers = new[] { (Id: 1, Name: "Ada"), (Id: 2, Name: "Bo"), (Id: 3, Name: "Cy") };int[] orderCustomers = { 1, 1, 3 };var counts = from c in customers join id in orderCustomers on c.Id equals id into matches orderby c.Id select (c.Name, Count: matches.Count());foreach (var row in counts) Console.WriteLine($"{row.Name}: {row.Count}");Ada matches twice; Bo still appears with zero matches. Each outer customer contributes one summary.
Expected output (reasoned, not executed):
Ada: 2Bo: 0Cy: 1Compare distinct sets
Distinct removes duplicates, Union combines distinct values from both inputs, Intersect finds shared distinct values, and Except finds distinct values in the first sequence not in the second. Concat differs by preserving duplicates. A comparer changes what counts as equal; use ordinal case-insensitive comparison for case-insensitive identifiers when appropriate.
using System;using System.Linq;string[] first = { "A", "A", "B" };string[] second = { "b", "C" };var cmp = StringComparer.OrdinalIgnoreCase;Console.WriteLine(first.Distinct(cmp).Count());Console.WriteLine(first.Union(second, cmp).Count());Console.WriteLine(first.Intersect(second, cmp).Count());Console.WriteLine(first.Except(second, cmp).Count());Console.WriteLine(first.Concat(second).Count());A and B are distinct in first. B and b compare equal, so union contains three equivalence classes, intersection one, and difference one. Concat has all five original items.
Expected output (reasoned, not executed):
23115Common mistakes and edge cases
Do not use Join to guarantee unique results or assume unmatched keys remain. Validate keys before joining if missing or duplicate identifiers would violate the domain. The examples use non-null integer keys; define and test null-key policy separately before applying joins to nullable identifiers. Set operations are not multiset arithmetic. Explicitly sort when presentation order matters; do not rely on implementation iteration order for set results.
Practice and recap
Join order keys [1,1,2,4] against customer keys [1,2,3]. Count pairs, then group-join customer keys to orders and record group sizes. Compare distinct union and intersection sizes.
Hint: Repeated order key 1 produces two join pairs; group join preserves customers.
Learning objective: Predict matches, duplicates and unmatched values. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Joins and set operators — knowledge check
Apply the lesson concepts to the following scenarios.
What happens to an outer item with no match in Join?
Two outer items match two inner items each. How many pairs?
What does GroupJoin provide for a customer with no orders?
Which operation preserves all duplicates when combining inputs?
With OrdinalIgnoreCase, do B and b count as equal in a string set operation?