Find duplicates in List
I have the following code:
List<MyType> myList = new List<MyType>();
// ... add items to the l开发者_JAVA百科ist
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.
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
.
精彩评论