包含相同元素的两个数组可以不相等吗? [英] Can two arrays which contain the same elements not be equal?

查看:87
本文介绍了包含相同元素的两个数组可以不相等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到一个令人震惊的问题,我试图查找List集合中是否包含对象.问题是列表找不到对象,并且当我已经可以看到索引时就返回索引为-1.然后,我创建了一个自定义的 Index Finder ,通过比较属性而不是直接相等来查找对象,我发现对象的一个​​属性,即一个相同的ushort数组,在比较时返回false,但它们包含的元素完全相同.

I encountered a stunning problem today where I'm trying to find if an object is contained in an List collection. The problem is that the list doesn't find the object and returns index as -1 when I can see it right there already. I then created a custom Index Finder to look for the object by comparing the properties rather than a direct equality where I discovered that one of the object's properties, a ushort array which was identical was returning false when compared, but they contain exactly the same element.

该数组如下:

{ushort [1]} [0] 13

{ushort[1]} [0]13

,两者完全相同,只是其中一个对象包含在一个列表中,而另一个对象则独立存在.造成此问题的原因是什么?我已经尝试了各种类型的方法来解决问题,但是我不能仅仅弄清楚问题是什么.在这种特殊情况下,导致两个数组之间的比较返回false的原因是,我使用了 Object.equals 和普通的 == 比较器.谢谢

and they're exactly the same in both except that one of the object is contained in a List while the other one is on it's own. What could be the cause of this problem? I've tried all types of different ways to get around the problem but I can't just figure out what the problem is. In this particular case what is causing the comparison between the two arrays to return false, I've tied using Object.equals as well as the normal == comparer. Thanks

推荐答案

对于数组,仅当您比较两个指向同一数组的引用时,Equals才会返回true.要按内容比较不同的数组,可以使用:

For arrays, Equals will return true only if you compare two references that point to the same array. To compare different arrays by content, you can use:

 Enumerable.SequenceEqual(a1, a2)

此外,如果collection包含您的自定义类型的对象,请确保这些类型覆盖Equals,equalityoperator(==)和GetHashCode.

Also, if collection contains objects of your custom type, make sure that these types override Equals, equality operator(==) and GetHashCode.

这篇关于包含相同元素的两个数组可以不相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆