Skip to main content

How to Remove Duplicates with LINQ Distinct in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

rolls.Distinct() returns every value in rolls once: the die rolls 3, 6, 3, 1, 6, 6, 2 become 3, 6, 1, 2. The array itself doesn't change, so you store what Distinct returns.

Microsoft's reference: Returns distinct elements from a sequence by using the default equality comparer to compare values. Distinct elements are different values: a value that appears several times appears once in the result. The remarks explain how values are compared. The method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.

A second form takes your own comparer: Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values. That's how you make red and RED count as the same color.

Syntax​

Syntax
IEnumerable<T> <result> = <items>.Distinct();
IEnumerable<T> <result> = <items>.Distinct(<comparer>);
PartWhat it is
<items>Any sequence, such as an array or a List<T>
<comparer>Optional: decides which values count as the same, such as StringComparer.OrdinalIgnoreCase to ignore upper and lower case
<result>A new sequence with each value once. <items> stays as it was. Add .ToArray() or .ToList() to keep the result as an array or a list
TThe type of the items, such as int or string

The Example​

A console app called LinqDistinct removes the repeated numbers from seven rolls of a die. Then it removes repeated colors, once with upper and lower case counting and once without, and uses Distinct to check whether every number in a list is different.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n LinqDistinct
cd LinqDistinct
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/LinqDistinct/LinqDistinct.csproj:
Determining projects to restore...
Restored /Users/you/source/LinqDistinct/LinqDistinct.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n LinqDistinct creates a folder named LinqDistinct with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or LinqDistinct.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the rolls:

Program.cs (the rolls)
// Seven rolls of a die: 3 and 6 come up more than once.
int[] rolls = [3, 6, 3, 1, 6, 6, 2];

// Distinct returns each value once.
int[] numbers = rolls.Distinct().ToArray();
Console.WriteLine($"Rolls: {string.Join(", ", rolls)}");
Console.WriteLine($"Distinct: {string.Join(", ", numbers)}");
Console.WriteLine($"{rolls.Length} rolls, {numbers.Length} different numbers");

rolls.Distinct() returns each number once, as an IEnumerable<int>, a sequence you can loop over. .ToArray() stores that sequence in a new array, numbers. string.Join(", ", ...) writes the values with a comma between them, and Length counts them.

Then the colors:

Program.cs (the colors)
// Strings that differ only in upper and lower case still count as different.
string[] colors = ["red", "Blue", "red", "RED", "blue", "green"];
Console.WriteLine($"Colors: {string.Join(", ", colors.Distinct())}");

// A comparer decides which values are the same: this one ignores case.
Console.WriteLine($"Ignoring case: {string.Join(", ", colors.Distinct(StringComparer.OrdinalIgnoreCase))}");

The first Distinct() compares the colors exactly as they're written. The second passes StringComparer.OrdinalIgnoreCase, a comparer that treats red and RED as the same string, and Blue and blue too.

Last, a check that every value is different:

Program.cs (every value different)
// Every value is different when Distinct keeps them all.
Console.WriteLine($"7, 19, 23, 41 all different: {AllDifferent([7, 19, 23, 41])}");
Console.WriteLine($"7, 19, 23, 7 all different: {AllDifferent([7, 19, 23, 7])}");

static bool AllDifferent(int[] values) => values.Distinct().Count() == values.Length;

AllDifferent compares the number of values left after Distinct with the number before. If none was removed, every value is different. It's a small method at the end of the file: => returns the value of the expression after it, and [7, 19, 23, 41] passes four numbers as an int[].

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Rolls: 3, 6, 3, 1, 6, 6, 2
Distinct: 3, 6, 1, 2
7 rolls, 4 different numbers
Colors: red, Blue, RED, blue, green
Ignoring case: red, Blue, green
7, 19, 23, 41 all different: True
7, 19, 23, 7 all different: False

macOS-style terminal window titled Terminal — LinqDistinct showing dotnet run printing the rolls 3, 6, 3, 1, 6, 6, 2, then Distinct: 3, 6, 1, 2 and 7 rolls, 4 different numbers, then Colors: red, Blue, RED, blue, green and Ignoring case: red, Blue, green, and last True for 7, 19, 23, 41 and False for 7, 19, 23, 7

The 7 rolls held 4 different numbers: the repeats of 3 and 6 were dropped. Plain Distinct() removed only the second red from the six colors, and kept RED and blue, which are written differently from red and Blue. With StringComparer.OrdinalIgnoreCase, the three reds counted as one value and so did the two blues, which left 3 colors, each in the spelling that came first. AllDifferent returned True for 7, 19, 23, 41 and False for 7, 19, 23, 7, where 7 appears twice.

The Complete File​

macOS-style code window titled Program.cs — LinqDistinct showing an array of seven die rolls, Distinct with ToArray, the rolls, the distinct numbers and both counts printed, an array of six colors printed after Distinct and after Distinct with StringComparer.OrdinalIgnoreCase, and an AllDifferent method that compares the count after Distinct with the length of the array

Program.cs
// Seven rolls of a die: 3 and 6 come up more than once.
int[] rolls = [3, 6, 3, 1, 6, 6, 2];

// Distinct returns each value once.
int[] numbers = rolls.Distinct().ToArray();
Console.WriteLine($"Rolls: {string.Join(", ", rolls)}");
Console.WriteLine($"Distinct: {string.Join(", ", numbers)}");
Console.WriteLine($"{rolls.Length} rolls, {numbers.Length} different numbers");

// Strings that differ only in upper and lower case still count as different.
string[] colors = ["red", "Blue", "red", "RED", "blue", "green"];
Console.WriteLine($"Colors: {string.Join(", ", colors.Distinct())}");

// A comparer decides which values are the same: this one ignores case.
Console.WriteLine($"Ignoring case: {string.Join(", ", colors.Distinct(StringComparer.OrdinalIgnoreCase))}");

// Every value is different when Distinct keeps them all.
Console.WriteLine($"7, 19, 23, 41 all different: {AllDifferent([7, 19, 23, 41])}");
Console.WriteLine($"7, 19, 23, 7 all different: {AllDifferent([7, 19, 23, 7])}");

static bool AllDifferent(int[] values) => values.Distinct().Count() == values.Length;

Common Mistakes​

MistakeWhat happensDo this instead
Calling Distinct on objects of a classThree objects of a Guest class with a Name property, two of them named Ana, printed Guests after Distinct: 3. The records reference explains it: For class types, two objects are equal if they refer to the same object in memory.Use DistinctBy with the property that makes two items the same: guests.DistinctBy(guest => guest.Name) printed Guests after DistinctBy: Ana, Ben. Or declare record Guest(string Name);, and Distinct() printed Guests after Distinct: 2
Passing a lambda to Distinctguests.Distinct(guest => guest.Name) didn't build: error CS1660: Cannot convert lambda expression to type 'IEqualityComparer<Guest>' because it is not a delegate typeDistinct takes a comparer, not a lambda. DistinctBy takes the lambda: guests.DistinctBy(guest => guest.Name)
Calling Distinct and not using its resultAfter rolls.Distinct();, the list still printed Rolls: 3, 6, 3, 1Store what it returns, as the example does: int[] numbers = rolls.Distinct().ToArray();

FAQ​

Does Distinct keep the original order?​

In the run it did: 3, 6, 1, 2 is the order in which each number first appeared. The reference doesn't promise it, though: The result sequence is unordered. When you need the values in a set order, sort them after Distinct. rolls.Distinct().Order() printed Sorted: 1, 2, 3, 6.

When does Distinct remove the duplicates?​

When you read the result, not when you call Distinct. The reference: This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. So a value added to the list after the call still shows up, unless ToArray() has already read the result:

Program.cs (deferred execution)
List<int> rolls = [3, 6, 3];
IEnumerable<int> different = rolls.Distinct();
int[] differentNow = rolls.Distinct().ToArray();
rolls.Add(5);
Console.WriteLine($"Distinct, read after Add: {string.Join(", ", different)}");
Console.WriteLine($"ToArray, called before Add: {string.Join(", ", differentNow)}");
Output
Distinct, read after Add: 3, 6, 5
ToArray, called before Add: 3, 6

How does DistinctBy decide what's a duplicate?​

By the key that your lambda returns. The reference: Returns distinct elements from a sequence according to a specified key selector function. Two guests named Ana have the same key, the name Ana, so DistinctBy kept one of them, and the Common Mistakes fix printed Ana, Ben.

Conclusion​

Distinct returns each value of a sequence once and leaves the original as it is, so store its result. Strings count as the same only when they match exactly, unless you pass a comparer such as StringComparer.OrdinalIgnoreCase. For objects of a class, use DistinctBy with the property that matters, or make the type a record. And when Distinct().Count() equals the length, every value is different.

Additional Resources​