比较两个 List在 C# 中
我有一个名为
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试以下
SequenceEquals 是
Enumerable
类上可用的扩展方法。默认情况下,它在 C# 3.5 项目中可用,因为它随 System.Linq 一起提供Try the following
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.LinqEnumerable.SequenceEqual
Enumerable.SequenceEqual
要回答你的问题,不,你不应该说实话。
List
和List
没有定义 .Equals,因此它们继承了 Object.Equals,它检查以下内容:以及
objA.Equals(objB) 是虚拟的。如果我没记错的话,默认实现只是检查引用相等性(指向内存中的同一对象),因此您的代码将返回 false。
To answer your question, no, you should not get true.
List
andList<T>
do not define .Equals, so they inherit Object.Equals, which checks the following: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.