I know you can use Enumerable.SequenceEqual to check equality. But a multidimensional array does not have such method. Any suggestion on how to compare 2 dimensional array?
Actual problem:
public class SudokuGrid
{
public Field[,] Grid
{
get { return grid; }
private set { grid = value; }
}
}
public class Field
{
private byte digit;
private bool isReadOnly;
private Coordinate coordinate;
private Field previousField;
private Field nextField;
}
All those properties are set in the SudokuGrid
constructor. So all those properties have private setters. I want to keep it that way.
Now, I'm doing some tests with C# unit tests. I want to compare 2 Grids
on their values rather then their references.
Since I set everything with private setters through constructor. This Equal override in class SudokuGrid
is correct, but not what I need:
public bool Equals(SudokuGrid other)
{
if ((object)other == null) return false;
bool isEqual = true;
for (byte x = 0; x < this.Grid.GetLength(0); x++) // 0 represents the 1st dimensional array
{
for (byte y = 0; y < this.Grid.GetLength(1); y++) // 1 represents the 2nd dimensional array
{
if (!this.Grid[x, y].Equals(other.Grid[x, y]))
{
isEqual = false;
}
}
}
return isEqual;
}
It is not what I need since I'm doing testing. So if my actual sudoku is:
SudokuGrid actual = new SudokuGrid(2, 3);
then my expected sudoku can't just be:
SudokuGrid expected = new SudokuGrid(2, 3);
but should be:
Field[,] expected = sudoku.Grid;
So I can't use the class to compare it's grid property, since I can't just set the grid since setter is private. It would be stupid if I had to change my original code just so my unit testing could work.
Questions:
You could use the following extension method, but you would have to make Field
implement IComparable
public static bool ContentEquals<T>(this T[,] arr, T[,] other) where T : IComparable
{
if (arr.GetLength(0) != other.GetLength(0) ||
arr.GetLength(1) != other.GetLength(1))
return false;
for (int i = 0; i < arr.GetLength(0); i++)
for (int j = 0; j < arr.GetLength(1); j++)
if (arr[i, j].CompareTo(other[i, j]) != 0)
return false;
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With