Can .NET test arrays for equivalence and not just

2019-04-28 11:24发布

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

However, I'm looking for a way to compare arrays which would compare the internal values instead of refernces. Is there a built in way to do this in .NET?

Also, while I understand Equals comparing references, GetHashCode returns different values for these two arrays also, which I feel shouldn't happen, since they have the same internal values.

2条回答
对你真心纯属浪费
2楼-- · 2019-04-28 12:04

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.

查看更多
甜甜的少女心
3楼-- · 2019-04-28 12:06

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.

查看更多
登录 后发表回答