0

Does C# Linq Distinct has stopped working recently? Few months ago it was working like a charm now it is not. For example when I try to do this

Product[] products = { new Product { Name = "apple", Code = 9 }, 
                   new Product { Name = "orange", Code = 4 }, 
                   new Product { Name = "apple", Code = 9 }, 
                   new Product { Name = "lemon", Code = 12 } };

IEnumerable<Product> noduplicates =
products.Distinct();
foreach (var product in noduplicates)
Console.WriteLine(product.Name + " " + product.Code);

This code should produce the following output:
apple 9 
orange 4
lemon 12

But it produces the following output: apple 9 orange 4 apple 9 lemon 12

tabula
  • 243
  • 1
  • 4
  • 13
  • 5
    Can it be that the Product class had a CompareTo method implemented which was removed or changed? – Stilgar Jul 27 '16 at 08:54
  • 4
    Linq Distinct is working properly. But you are not using it correctly. Hint: implement `GetHashCode` and `Equals` in your `Product` class. – Ivan Stoev Jul 27 '16 at 08:54
  • 2
    You need to tell LINQ how you define equality between products by providing an `IEqualityComparer` or making `Product` implement `IEquatable`. – Jon Jul 27 '16 at 08:55
  • I stand corrected @IvanStoev mentioned the proper methods although the issue is pretty much the same. – Stilgar Jul 27 '16 at 08:55

0 Answers0