开发者

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; //???


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


Enumerable.SequenceEqual


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜