tags:

views:

89

answers:

1

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.

+4  A: 

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.

Jon Skeet
I missed `GetHashCode`. I'm adding it now.
a1ex07
@a1ex07: Hmm... the C# compiler should have warned you about that...
Jon Skeet
Thanks a lot. You were right, compiler did actually warn me about it, I should have figured it out by myself...
a1ex07