3

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; //???
Matt
  • 25,943
  • 66
  • 198
  • 303

3 Answers3

7

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

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
2

Enumerable.SequenceEqual

leppie
  • 115,091
  • 17
  • 196
  • 297
0

To answer your question, no, you should not get true. List and List<T> do not define .Equals, so they inherit Object.Equals, which checks the following:

public static bool Equals(object objA, object objB)
{
    return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB)));
}

And objA.Equals(objB) is virtual. If I recall correctly, the default implementation just checks for reference equality (pointing to the same object in memory), so your code would return false.

Pat
  • 16,515
  • 15
  • 95
  • 114