CodexBloom - Programming Q&A Platform

LINQ Distinct optimization guide as expected with custom objects in C# 10

👀 Views: 384 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
linq c# distinct custom-objects C#

I'm building a feature where I'm optimizing some code but I'm learning this framework and I'm sure I'm missing something obvious here, but I'm trying to use LINQ's `Distinct()` method on a list of custom objects, but I'm not getting the expected results... I've defined a class `Person` like this: ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } } ``` I have a list of `Person` objects, some of which have the same name and age, and I want to filter out duplicates based only on the combination of `Name` and `Age`. However, when I use `Distinct()`, it seems to return all the items, including duplicates. Here's the code I used: ```csharp var people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Bob", Age = 25 }, new Person { Name = "Charlie", Age = 35 } }; var distinctPeople = people.Distinct().ToList(); ``` When I output the count of `distinctPeople`, it shows 5 instead of 3. I understand that `Distinct()` uses reference equality by default, but I thought it would handle value equality for more complex types. To fix this, I implemented `IEqualityComparer<Person>` like this: ```csharp public class PersonComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { return x.Name == y.Name && x.Age == y.Age; } public int GetHashCode(Person obj) { return (obj.Name + obj.Age.ToString()).GetHashCode(); } } ``` Then I updated my LINQ query: ```csharp var distinctPeople = people.Distinct(new PersonComparer()).ToList(); ``` However, I'm still working with the same scenario. The count is still 5, and I am at a loss as to why the equality check doesn't seem to be working. Is there something I'm missing about how `Distinct()` interacts with `IEqualityComparer`? Any tips on how to properly use `Distinct()` with custom objects in C# 10 would be greatly appreciated. My development environment is Windows. How would you solve this? I'm on macOS using the latest version of C#. My development environment is Ubuntu 22.04. What would be the recommended way to handle this?