Can .NET test arrays for equivalence and not just equal references?

冷暖自知 提交于 2019-12-05 08:58:57

I believe you are looking for the Enumerable.SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) method.

var a = new double[] {1, 2, 3};
var b = new double[] {1, 2, 3};
System.Console.WriteLine(a.SequenceEqual(b)); // Returns true

As far as the issue with GetHashCode returning different values, remember that you are dealing with two distinct values here. You are not comparing arrays, you are comparing two references to arrays.

Default equality comparison for reference types needs to be consistent. If you need something else to happen remember there is a built in model for that using IEqualityComparer<T> which allows you to define custom equality comparison based on specific needs that don't follow the standard reference equality pattern.

E.Z. Hart

UPDATE: Fixed code to use the correct comparison method (thanks to @CodesInChaos for pointing that out).

If you're in .NET 4, you can use the IStructuralEquatable interface:

IStructuralEquatable c = b;
Console.WriteLine(c.Equals(a, StructuralComparisons.StructuralEqualityComparer));

This question has more detail.

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