Search code examples
c#listmergecompareexcept

Compare 2 Lists with Except() Method but it didnt work


I would like to compare with the Except Method 2 lists. Objects are stored in these lists.

If I use the Except method, nothing is filtered, although there are identical objects.

My goal:

I want to have all objects in the list "chkpoints" that are not in the list "chkpointslist".

What is the best way to do this or what am I doing wrong?

List<checkpoint> chkpoints = new List<checkpoint>();
List<checkpoint> chkpointslist = new List<checkpoint>();
chkpointslist = database.loadChecklistpoints(checklistid);
chkpoints = database.loadCheckpoint(type);
chkpoints = chkpoints.Except(chkpointslist).ToList();

Solution

  • Enumerable.Except uses the default equality comparer to compare values. So, if your checkpoint class doesn't have an IEquatable, all of your checkpoint instances will just be read as unique.

    From the .NET docs:

    If you want to compare sequences of objects of some custom data type, you have to implement the IEquatable<T> generic interface in a helper class.

    There are examples on how to create an IEquatable helper class on the Enumerable.Except docs (linked above).