Codectionary / Developer documentation / C#

Compare Sequences with LINQ Set Operations

Use Except, Intersect and Union with deliberate equality and explicit presentation order.

Read the syntax

Use Except, Intersect and Union with deliberate equality and explicit presentation order.

Intersect returns the common distinct value 2.

What it is and why to use it

A set comparison can find unfinished topics, common tags or the combined distinct values of two lists. Except computes a one-way difference, Intersect computes common values and Union combines distinct values. These operators apply set semantics, so duplicate occurrences are not retained as separate counts.

How it works

The default equality comparer determines whether values match, and comparer overloads let you choose another policy. These are deferred LINQ to Objects operations and may store values for membership tracking. Sort the result explicitly when an output format needs a clear order. Except(a, b) answers a different question from Except(b, a).

Common mistakes and limitations

Do not use set operations when duplicate frequency is meaningful. Do not assume object reference equality gives your intended record identity. These operators do not modify either source collection and do not automatically normalise text.

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

var missing = planned.Except(completed, comparer);

Examples

Compare two integer sets

Inspect difference, intersection and union after explicit ordering.

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

int[] first = { 1, 2, 2, 3 };
int[] second = { 2, 4 };
Console.WriteLine(string.Join(", ", first.Except(second).OrderBy(x => x)));
Console.WriteLine(string.Join(", ", first.Intersect(second).OrderBy(x => x)));
Console.WriteLine(string.Join(", ", first.Union(second).OrderBy(x => x)));
  1. Except retains values from first that are absent from second.
  2. Intersect returns the common distinct value 2.
  3. Union contains each distinct value once. The repeated input 2 does not appear twice.
  4. Expected output: 1, 3 2 1, 2, 3, 4
  5. Choose set or multiset semantics deliberately.

Find remaining case-insensitive topic IDs

Apply the same key policy to a completion comparison.

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

string[] planned = { "PHP", "C#", "Ruby" };
string[] completed = { "php" };
var remaining = planned.Except(completed, StringComparer.OrdinalIgnoreCase)
    .OrderBy(x => x, StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", remaining));
  1. The comparer treats PHP and php as equal, so that topic is excluded.
  2. The one-way comparison retains the planned topics that are not complete.
  3. Explicit ordinal ordering makes the display deterministic; the original lists are unchanged.
  4. Expected output: C#, Ruby
  5. Choose set or multiset semantics deliberately.

Best practices

  • Choose set or multiset semantics deliberately.
  • Use one consistent equality policy and sort for presentation.

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