---
title: "Why C# LINQ Distinct() doesn’t work?"  
description: "Why C# LINQ Distinct() doesn’t work?"  
author: "Sandra Emily"  
published: 2023-08-17  
updated: 2023-08-18  
canonical: https://www.mindstick.com/forum/159558/why-c-sharp-linq-distinct-doesn-t-work  
category: "c#"  
tags: ["c#", "linq", "lambda expression"]  
reading_time: 2 minutes  

---

# Why C# LINQ Distinct() doesn’t work?

Why C# [LINQ](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries) [Distinct](https://www.mindstick.com/forum/159569/how-to-use-a-lambda-expression-in-enumerable-distinct)(f=>f.propertyname) doesn’t work?

## Replies

### Reply by Aryan Kumar

The `Distinct()` method in LINQ is used to remove duplicates from a sequence. The `Distinct()` method takes an optional parameter that specifies the comparer to use when comparing elements. If the parameter is 0, the default comparer is used. The default comparer compares elements by their GetHashCode() method.

The GetHashCode() method returns a hash code for an object. The hash code is used to quickly compare elements in a hash table. However, the GetHashCode() method does not guarantee that two objects with different values will have different hash codes. This is why the `Distinct()` method with a parameter of 0 does not work.

To use the `Distinct()` method to remove duplicates, you need to specify a comparer that guarantees that two objects with different values will have different hash codes. You can use the `IEqualityComparer` interface to create a custom comparer.

The following code is an example of how to use the `Distinct()` method with a custom comparer:

C#

```plaintext
public class Person {
    public string Name { get; set; }
}

public class PersonComparer : IEqualityComparer<Person> {
    public bool Equals(Person x, Person y) {
        return x.Name == y.Name;
    }

    public int GetHashCode(Person obj) {
        return obj.Name.GetHashCode();
    }
}

var people = new List<Person>();
people.Add(new Person { Name = "John" });
people.Add(new Person { Name = "Jane" });
people.Add(new Person { Name = "John" });

var distinctPeople = people.Distinct(new PersonComparer());
```

In this code, the `PersonComparer` class implements the `IEqualityComparer` interface and provides a custom comparer for the `Person` class. The `Equals()` method compares the names of two `Person` objects and returns a value indicating whether the two objects are equal. The `GetHashCode()` method returns a hash code for a `Person` object.

The `distinctPeople` variable is a list that contains only the distinct `Person` objects from the `people` list.


---

Original Source: https://www.mindstick.com/forum/159558/why-c-sharp-linq-distinct-doesn-t-work

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
