简体   繁体   English

比较两个List <MyClass> 在C#中

[英]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. 这个类继承IEquatable并实现等于我需要它的方式。 (Meaning: when I compare two MyClass tyupe objects individually in code, it works) (含义:当我在代码中单独比较两个MyClass tyupe对象时,它可以工作)

I then create two List: 然后我创建两个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和ListB时,我应该得到真的吗?

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

Try the following 请尝试以下方法

ListA.SequenceEquals(ListB);

SequenceEquals is an extension method available on the Enumerable class. SequenceEquals是Enumerable类上可用的扩展方法。 This is available by default in C# 3.5 projects as it comes with System.Linq 这在C#3.5项目中是可用的,因为它随System.Linq一起提供

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: ListList<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. objA.Equals(objB)是虚拟的。 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. 如果我没记错的话,默认实现只是检查引用相等性(指向内存中的同一个对象),因此你的代码将返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM