Comparing two <MyClass> lists in C #

I have a class called

MyClass

This class inherits IEquatable and implements equal as I need it. (Meaning: when I compare two MyPrass tyupe objects individually in code, it works)

Then I create two lists:

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 the truth?

ListA.Equals(ListB)==true; //???
+3
source share
3 answers

Try to execute

ListA.SequenceEquals(ListB);

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

+7
source

, , . List List<T> .Equals, Object.Equals, :

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 remember correctly, the default implementation simply checks for reference equality (pointing to the same object in memory), so your code will return false.

0
source

Source: https://habr.com/ru/post/1736555/


All Articles