0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ Distinct in C# for Unique Collections

Use Distinct() in LINQ to remove duplicate elements from a collection in C#. It returns a new sequence with only unique items based on default equality or a custom comparer.
📐

Syntax

The Distinct() method is called on a collection to return unique elements. You can optionally provide a custom equality comparer.

  • collection.Distinct(): Returns unique elements using default equality.
  • collection.Distinct(IEqualityComparer<T> comparer): Uses a custom comparer to determine uniqueness.
csharp
var uniqueItems = collection.Distinct();
💻

Example

This example shows how to use Distinct() to remove duplicate numbers from a list and print the unique values.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
        var uniqueNumbers = numbers.Distinct();

        foreach (var num in uniqueNumbers)
        {
            Console.WriteLine(num);
        }
    }
}
Output
1 2 3 4 5
⚠️

Common Pitfalls

One common mistake is expecting Distinct() to work on complex objects without overriding equality. By default, it compares references for objects, so duplicates may not be removed as expected.

To fix this, implement IEquatable<T> or provide a custom IEqualityComparer<T>.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 }
        };

        // This will NOT remove duplicates because default compares references
        var distinctPeople = people.Distinct();
        Console.WriteLine("Count without comparer: " + distinctPeople.Count());

        // Using custom comparer
        var distinctPeopleWithComparer = people.Distinct(new PersonComparer());
        Console.WriteLine("Count with comparer: " + distinctPeopleWithComparer.Count());
    }
}

class PersonComparer : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        if (x == null && y == null) return true;
        if (x == null || y == null) return false;
        return x.Name == y.Name && x.Age == y.Age;
    }

    public int GetHashCode(Person obj)
    {
        return HashCode.Combine(obj.Name, obj.Age);
    }
}
Output
Count without comparer: 3 Count with comparer: 2
📊

Quick Reference

  • Distinct(): Removes duplicates using default equality.
  • Distinct(IEqualityComparer<T>): Removes duplicates using custom logic.
  • Works on any IEnumerable<T> collection.
  • Returns a new sequence; original collection is unchanged.

Key Takeaways

Use Distinct() to get unique elements from collections easily.
For custom objects, provide an IEqualityComparer<T> or override equality to remove duplicates correctly.
Distinct() returns a new sequence and does not modify the original collection.
It works on any collection implementing IEnumerable<T>.
Remember that default equality for objects compares references, not content.