How to get comparison items in a general list

I have a custom class that implements this IComparable. This class is stored in a common list. Now I need to compare with lists to see which objects are in list A, but not in list B.

I thought the easiest way to do this is to iterate over list B and do A.contains ().

I don't know how to get it to use my CompareTo () (or another method that I can override so that I can tell if it contains a specific object or not). I could be wrong, but, as I understand it, it contains checks if the objects are actually the same (i.e. indicates the same place in memory).

Can anyone help me?

+3
source share
5 answers

Equals , CompareTo(other) == 0? , , , , Contains , CompareTo. Equals. , .

/EDIT: , .NET 3.5, Contains, IEqualityComparer . , , . , , .

+5

, 3.5, :

list notInB = A (listB.find(function (x) x.property = item.property) = ) select item

A, B.

linq , , -. , (& &) (||)

, IComparable.

+1

. ! IComparable, , .contains.

:)

0

, (.. )

, , . , EqualsTo.

I agree with Rudolph that you are trying to overload EqualsTo () first.

0
source

There is also IEquatable, and if your object implements this interface, it is automatically used by all generic collections, if implemented. Although I never understood why it exists in the first place, since the docs say that if you implement IEquatable, then you should also override Equals to match. Also remember, if you are going to override Equals, you also need to override GetHashCode.

0
source

Source: https://habr.com/ru/post/1698477/


All Articles