Codectionary / Developer documentation / C#

Choose Distinct Keys with DistinctBy

Deduplicate using a selected key while deciding conflict and presentation policies separately.

Read the syntax

Deduplicate using a selected key while deciding conflict and presentation policies separately.

The repeated ID 1 contains the same demonstration data, so no conflict policy is needed here.

What it is and why to use it

Two records may represent the same ID even though their full object values differ. DistinctBy, introduced in .NET 6, compares selected keys rather than entire records. It is useful for benign repeated data, but it does not merge fields or decide which conflicting record should be authoritative in an import.

How it works

Supply a key selector and optionally an equality comparer. The operation is deferred and tracks seen keys during enumeration. Its public result is described as unordered, so sort explicitly for stable presentation. If duplicate records disagree, define an explicit grouping and selection policy instead of relying on incidental enumeration behaviour.

Common mistakes and limitations

Do not silently discard conflicting authoritative data. Do not assume deduplication guarantees a sorted output. A custom key comparer must reflect the domain’s intended equality, and its hashing must agree with that equality.

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 distinct = items.DistinctBy(item => item.Id);

Examples

Remove identical repeated records by ID

Use duplicates that agree, then explicitly order the displayed results.

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

var learners = new[] { (Id: 2, Name: "James"), (Id: 1, Name: "John"), (Id: 1, Name: "John") };
foreach (var learner in learners.DistinctBy(x => x.Id).OrderBy(x => x.Id))
    Console.WriteLine($"{learner.Id}: {learner.Name}");
  1. The key selector compares learner IDs.
  2. The repeated ID 1 contains the same demonstration data, so no conflict policy is needed here.
  3. OrderBy supplies an explicit final order. DistinctBy itself is not used as a sorting contract.
  4. Expected output: 1: John 2: James
  5. Separate duplicate-key detection from conflict resolution.

Deduplicate a case-insensitive label key

Normalise the output representation after comparing identifiers.

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

string[] labels = { "php", "PHP", "ruby" };
var canonical = labels.DistinctBy(x => x, StringComparer.OrdinalIgnoreCase)
    .Select(x => x.ToUpperInvariant()).OrderBy(x => x, StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", canonical));
  1. The comparer treats php and PHP as the same logical key.
  2. The selected representative is converted to a deliberate uppercase display form.
  3. The final ordinal ordering makes the rendered output independent of the distinct sequence’s ordering contract.
  4. Expected output: PHP, RUBY
  5. Separate duplicate-key detection from conflict resolution.

Best practices

  • Separate duplicate-key detection from conflict resolution.
  • Order explicitly when output needs a stable 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