Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare multidimensional arrays on equality?

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:

  • So is their a way to actually compare multidimensional arrays? (So can I maybe override the equal method an multidimensional array uses?)
  • Is there maybe another way to solve my problem?
like image 216
dylanmensaert Avatar asked Nov 03 '22 02:11

dylanmensaert


1 Answers

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;
}
like image 198
FlyingStreudel Avatar answered Nov 09 '22 10:11

FlyingStreudel