Search code examples
c#linqequality

Determine how List<IMyInterface>.Except() is comparing items


I have read about Except here. I am still a bit confused. I am using .NET 4.8.

I have 7 different implementations of my custom interface IMyInterface. All these implementations are held in a List or IEnumerable. I am doing the following in many places of my project (pseudocode):

List<IMyInterface> myList = //some items
List<IMyInterface> anotherList = //some more items
var difference = myList.Except(anotherList);

I think I am getting some not correct results. Looking into the issue a bit it seems that .NET compares equality by if the two objects pointers are the same. In my case some of these elements that I will be comparing will be copies so the tra=ditional Equals will fail. I definitely need to create a custom comparer.

I created methods on all these implementations that override Equals(). Example:

public override bool Equals(object obj)
{
    if (obj is null or not Arc) return false;
    var testObj = (Arc)obj;
    if (Key.SequenceEqual(testObj.Key)) return true;
    return false;
}

I then set breakpoints in all the new Equals() methods to tell if that custom Equals() method is being used.

I know that Linq does not execute until the data is needed. If I allow a line like this to run:

var difference = myList.Except(anotherList);

and then check the value of the variable difference by hovering over it in break mode there are results but my breakpoints never get hit.

How do I tell with certainty what Except() is using in my environment to make the determination of equality on my custom objects?


Solution

  • To use an Except in case of comparing list of objects, those objects should implement IEquatable<T>. In Your case the T should be IMyInterface to be safe.

    Alternatively you could use overload that takes the custom comparer that derives from IEqualityComparer<IMyInterface>.

    More info can be found here.