CodexBloom - Programming Q&A Platform

LINQ Distinct with Complex Object Properties optimization guide as Expected

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
linq c# distinct comparer csharp

I'm working through a tutorial and I'm working with a collection of custom objects in C# and trying to filter duplicates based on a specific property using LINQ's `Distinct`. However, it's not behaving as I expected. Here's my object definition: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` I have a list of `Product` objects: ```csharp var products = new List<Product> { new Product { Id = 1, Name = "Apple", Price = 1.00m }, new Product { Id = 2, Name = "Banana", Price = 0.50m }, new Product { Id = 1, Name = "Apple", Price = 1.00m }, // Duplicate new Product { Id = 3, Name = "Orange", Price = 0.75m } }; ``` When I try to filter out duplicates using: ```csharp var distinctProducts = products.Distinct().ToList(); ``` I expected the duplicate "Apple" product to be removed, but it remains in the list. I learned that `Distinct` uses reference equality by default. To resolve this, I implemented `IEqualityComparer<T>` as follows: ```csharp public class ProductComparer : IEqualityComparer<Product> { public bool Equals(Product x, Product y) { if (x == null || y == null) return false; return x.Id == y.Id; } public int GetHashCode(Product obj) { return obj.Id.GetHashCode(); } } ``` Then I used it like this: ```csharp var distinctProducts = products.Distinct(new ProductComparer()).ToList(); ``` To my surprise, the results are still not what I expected. The output still contains duplicates. I'm not sure where I went wrong. Have I implemented `IEqualityComparer` correctly? Is there a better way to achieve distinct items based on complex properties? Any guidance would be appreciated! I'd really appreciate any guidance on this. I'm developing on Debian with Csharp. Thanks, I really appreciate it!