Can two arrays which contain the same elements not be equal?

岁酱吖の 提交于 2021-02-05 07:58:24

问题


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.

The array is as follows:

{ushort[1]} [0]13

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


回答1:


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)

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



来源:https://stackoverflow.com/questions/16002903/can-two-arrays-which-contain-the-same-elements-not-be-equal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!