2

I use .net 2.0 (C#)

I have a Person class, and i pupulate List< Person> p from the database.

i know for a fact that my list has duplicates, but when i try to remove the duplicates they don't get removed.

Does my Person class need to implement any interfaces for List< T>.Contains(T) to work properly?

Any other ideas?

Thank you.

Community
  • 1
  • 1
roman m
  • 26,012
  • 31
  • 101
  • 133

5 Answers5

8

Your Person class should implement IEquatable

BFree
  • 102,548
  • 21
  • 159
  • 201
4

You should override Equals and GetHashCode method.

redjackwong
  • 1,568
  • 2
  • 12
  • 14
  • 1
    While this DOES work, implementing IEquatable is better because it's type safe, whereas Equals is not. – BFree Feb 27 '09 at 01:29
  • Agree. But I think you should still override your GetHashCode method. This gives you better performance. – redjackwong Feb 27 '09 at 02:05
1

The example you reference is not a solution for removing dupes from a list, it is a function that takes a list and yields an iterator that will exclude duplicates. If you need to dedupe the entire list in one go you would need to take the IEnumerable<T> returned from the function and pass it into a new List<T>.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • thanx for detail, i used that code as a reference to fill a new List from the original by checking .Contains() on the new list on ever iteration – roman m Feb 27 '09 at 01:20
1

You need to overload Object.Equals(Object obj) in your class.

Trevor
  • 719
  • 1
  • 6
  • 15
0

The docs say "This method determines equality using the default equality comparer EqualityComparer(T).Default".

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78