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

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

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.