I have a custom class that implements that IComparable. This class is stored in a Generic List. I now need to compare to lists to see which objects are in list A but not in list B.
I thought the most simple way of doing this would be to iterate through list B and do A.contains().
I do not know how to get it to use my CompareTo() (or another method that I can override so that I can say if it contains a certain object or not). I could be wrong but as I understand it the contains checks if the objects are actually the same (i.e. points to the same place in memory).
Could anyone help me please?
Why don’t you just override the
Equalsmethod of your class to be consistent in meaning withCompareTo(other) == 0? This is the simplest way and also the most idiomatic since, as you’ve noticed,Containscompares equality rather than usingCompareTo. However, this check is done viaEquals. It does not check whether the objects point to the same memory location./EDIT: Additionally, if you’re using .NET 3.5 you can use the
Containsoverload that accepts anIEqualityComparerargument. You can use this to provide a class that implements a custom equality relation for your class type. However, I think the first method is more appropriate in your case.