I want to be able to compare 2 jagged arrays of doubles for value equality. The arrays can have any number of dimensions. Inside any dimension could also be another array etc.
It is known that the values of any array dimension is a double, null or another array, so it should be able to compare any of these with one function:
double[]
double[][]
double[][][]
double[][double[]][double[][]]
public static bool ArraysEqual(dynamic a, dynamic b)
{
// Same objects or both null
if (ReferenceEquals(a, b)) return true;
// Just one object is null
if (a == null ^ b == null) return false;
// Different number of elements
if (a.Length != b.Length) return false;
// Array is empty
if (a.Length == 0) return true;
// Test each item in the arrays
for (int i = 0; i < a.Length; i++)
{
// Same object or both null
if (ReferenceEquals(a[i], b[i])) continue;
// Just one object is null
if (a[i] == null ^ b[i] == null) return false;
var aIsArray = a[i].GetType().IsArray;
var bIsArray = b[i].GetType().IsArray;
// Just one object is an array
if (aIsArray ^ bIsArray) return false;
// Both are arrays (no need to check b, since it was exclusive or'd prior)
// Stop evaluating if the recursive call returned false;
if (aIsArray)
{
if (!ArraysEqual(a[i], b[i])) return false;
}
else if (a[i] != b[i])
{
return false;
}
}
return true;
}