a1ex07
a1ex07

Reputation: 37364

Find duplicates in List

I have the following code:

List<MyType> myList = new List<MyType>();
// ... add items to the list
var dupes = myList.GroupBy(g => g).Where(x => (x.Count() > 1))
                  .Select(x => new { obj = x.Key, count = x.Count() }).ToList();

dupe is always empty, even if I intentionally insert duplicates into the list. What should I add to MyType definition to make it work ? I implemented Equals(object obj) and CompareTo(object obj) for MyType, but none of these methods gets called.

Upvotes: 1

Views: 644

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500825

Have you implemented GetHashCode correctly, to match your Equals method? It won't be using CompareTo (that's for ordering) but will use GetHashCode and Equals.

If you believe you've done that already, please post the code for Equals and GetHashCode.

Upvotes: 4

Related Questions