In Java, Arrays.equals() allows to easily compare the content of two basic arrays (overloads are available for all the basic types).
Is there such a thing in C# ? Is there any "magic" way of comparing the content of two arrays in C# ?
In Java, Arrays.equals() allows to easily compare the content of two basic arrays (overloads are available for all the basic types).
Is there such a thing in C# ? Is there any "magic" way of comparing the content of two arrays in C# ?
You could use SequenceEqual. This works for any IEnumerable<T>
, not just arrays.
Use SequenceEqual in Linq.
int[] arr1 = new int[] { 1,2,3};
int[] arr2 = new int[] { 3,2,1 };
Console.WriteLine(arr1.SequenceEqual(arr2)); // false
Console.WriteLine(arr1.Reverse().SequenceEqual(arr2)); // true
Also for arrays (and tuples) you can use new interfaces from .NET 4.0: IStructuralComparable and IStructuralEquatable. Using them you can not only check equality of arrays but also compare them.
static class StructuralExtensions
{
public static bool StructuralEquals<T>(this T a, T b)
where T : IStructuralEquatable
{
return a.Equals(b, StructuralComparisons.StructuralEqualityComparer);
}
public static int StructuralCompare<T>(this T a, T b)
where T : IStructuralComparable
{
return a.CompareTo(b, StructuralComparisons.StructuralComparer);
}
}
{
var a = new[] { 1, 2, 3 };
var b = new[] { 1, 2, 3 };
Console.WriteLine(a.Equals(b)); // False
Console.WriteLine(a.StructuralEquals(b)); // True
}
{
var a = new[] { 1, 3, 3 };
var b = new[] { 1, 2, 3 };
Console.WriteLine(a.StructuralCompare(b)); // 1
}