比较两个 List在 C# 中

发布于 2024-08-24 09:56:25 字数 490 浏览 6 评论 0原文

我有一个名为

MyClass

该类继承 IEquatable 并实现 equals 我需要它的方式。 (意思是:当我在代码中单独比较两个 MyClass 类型对象时,它可以工作)

然后我创建两个列表:

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.

当我去比较 ListA 和 ListB 时,我应该得到 true 吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

或十年 2024-08-31 09:56:25

尝试以下

ListA.SequenceEquals(ListB);

SequenceEquals 是 Enumerable 类上可用的扩展方法。默认情况下,它在 C# 3.5 项目中可用,因为它随 System.Linq 一起提供

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

半葬歌 2024-08-31 09:56:25

要回答你的问题,不,你不应该说实话。 ListList 没有定义 .Equals,因此它们继承了 Object.Equals,它检查以下内容:

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

以及 objA.Equals(objB) 是虚拟的。如果我没记错的话,默认实现只是检查引用相等性(指向内存中的同一对象),因此您的代码将返回 false。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文