I needed to find the difference between the two collections , the elements of the collection are instances of the user class.
To find the difference, I want to use the linq method Except , the method description says that for user types you need to do one of two things:
Inherit the custom class from IEquatable<T> and override the Equals & GetHashCode methods in the source class.
public class OperationItem: IEquatable<OperationItem> { public bool Equals(OperationItem other) { if (other is null) return false; return this.Name == other.Name && this.Code == other.Code; } public override bool Equals(object obj) => Equals(obj as OperationItem); public override int GetHashCode() => (Name, Code).GetHashCode(); } Or create the comparator we need by implementing the IEqualityComparer<T> interface and implementing the Equals & GetHashCode methods we already know.
public class OperationItemComparer: IEqualityComparer<OperationItem> { public bool Equals(OperationItem x, OperationItem y) { /*Реализация*/ } public int GetHashCode(OperationItem obj) { /*Реализация*/ } } Is there a significant difference in the use of this or that method, I assume that the second method is used in case of impossibility to change the original class, but maybe there are other reasons for using one or another method?