Deduplicate LINQ results with an explicit winner policy
Deduplication requires an equality rule and a survivor rule. “One record per email address” describes the key, but it does not say whether the newest, oldest or most complete record should survive. Separate those decisions before writing the query.
Use DistinctBy when any representative of an equal key is acceptable. If records carry different business values, group by the key and explicitly select the desired winner. Add an output sort when callers require a stable presentation order.
Run both operations
Create a .NET 10 console project with dotnet new console -n DedupDemo -f net10.0. Replace Program.cs and run dotnet run --project DedupDemo from the parent directory. This example uses LINQ to Objects over an in-memory array.
using System;
using System.Linq;
var rows = new[] {
new Contact(4, "[email protected]", new DateOnly(2026, 2, 1), "Old"),
new Contact(3, "[email protected]", new DateOnly(2026, 3, 1), "Newer"),
new Contact(2, "[email protected]", new DateOnly(2026, 3, 1), "Tie winner"),
new Contact(5, "[email protected]", new DateOnly(2026, 1, 1), "Other")
};
var keyComparer = StringComparer.OrdinalIgnoreCase;
var representatives = rows.DistinctBy(x => x.Email, keyComparer).ToArray();
Console.WriteLine($"Unique keys={representatives.Length}");
var winners = rows
.GroupBy(x => x.Email, keyComparer)
.Select(group => group.OrderByDescending(x => x.Updated)
.ThenBy(x => x.Id).First())
.OrderBy(x => x.Email, keyComparer)
.ToArray();
foreach (var row in winners) {
Console.WriteLine($"{row.Id} {row.Email} {row.Label}");
}
Console.WriteLine($"Original rows={rows.Length}");
Console.WriteLine($"Empty keys={Array.Empty<Contact>().DistinctBy(x => x.Email).Count()}");
sealed record Contact(int Id, string Email, DateOnly Updated, string Label);
Expected output:
Unique keys=2
5 [email protected] Other
2 [email protected] Tie winner
Original rows=4
Empty keys=0
The winner for the reader key has the newest update date. Two records share that date, so the smaller ID breaks the tie. The original array remains unchanged. ToArray materializes the result so later reads do not rerun the query against changing source data.
Make equality a domain decision
The sample intentionally treats its demonstration email keys as ordinal case-insensitive identifiers. That is the application's rule for this dataset, not a universal statement about email address equivalence. Real systems should use the normalization and identity policy defined for their keys.
A comparer controls equality without rewriting the stored value. Consequently, a selected record can retain different capitalization from another equal record. If output must use a canonical spelling, compute and store that representation separately.
Decide how missing keys behave. LINQ grouping can put null keys together, but “all unknown people are the same person” is usually an unsafe inference. Validate required keys or route unkeyed records through a separate policy. Trimming whitespace and ignoring accents also change equality and should be explicit.
Specify the survivor rather than relying on incidental order
Microsoft describes the DistinctBy result as unordered. It is useful for selecting representatives, but it does not express a newest-record business policy. Sorting the final result also does not recover information already discarded during deduplication. The grouped query makes both the winning comparison and its tie-breaker visible.
Use an additional unique tie-breaker if duplicate IDs can occur. Otherwise equal dates and equal IDs still leave a tie whose winner depends on input order. For financial or audit-sensitive data, rejecting contradictory duplicates may be more appropriate than selecting one silently.
DistinctBy uses deferred execution, and grouping plus sorting requires retaining data. Consider input size and enumerate once when a stable snapshot matters. For IQueryable from a database provider, verify translation and database comparison rules. This in-memory example does not establish that a provider supports the same query or uses the same string collation.
References



Question provenance
This article addresses LINQ's Distinct() on a particular property , asked by Patrick Desjardins on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.
Author: Herman Schoenfeld