Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Compare items in a Generic List

Tags:

c#

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?

like image 715
Jon Avatar asked Dec 13 '25 03:12

Jon


1 Answers

Why don't you just override the Equals method of your class to be consistent in meaning with CompareTo(other) == 0? This is the simplest way and also the most idiomatic since, as you've noticed, Contains compares equality rather than using CompareTo. However, this check is done via Equals. 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 Contains overload that accepts an IEqualityComparer argument. 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.

like image 114
Konrad Rudolph Avatar answered Dec 14 '25 16:12

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!