Search code examples
c#.netlistiequatableiequalitycomparer

Comparing two List<MyClass> in C#


I have a class called

MyClass

This class inherits IEquatable and implements equals the way I need it to. (Meaning: when I compare two MyClass tyupe objects individually in code, it works)

I then create two List:

var ListA = new List<MyClass>();
var ListB = new List<MyClass>();
// Add distinct objects that are equal to one another to 
// ListA and ListB in such a way that they are not added in the same order.

When I go to compare ListA and ListB, should I get true?

ListA.Equals(ListB)==true; //???

Solution

  • Try the following

    ListA.SequenceEquals(ListB);
    

    SequenceEquals is an extension method available on the Enumerable class. This is available by default in C# 3.5 projects as it comes with System.Linq