如何在相等上比较多维数组

本文关键字:比较 数组 | 更新日期: 2023-09-27 18:03:50

我知道你可以使用Enumerable。SequenceEqual检查是否相等。但是多维数组没有这样的方法。任何关于如何比较二维数组的建议?

实际问题:

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;
}

所有这些属性都在SudokuGrid构造函数中设置。所有这些属性都有private setter。我想保持这种状态。

现在,我正在用c#单元测试做一些测试。我想比较两个Grids的值,而不是它们的引用。

因为我通过构造函数设置了所有私有setter。这等于覆盖类SudokuGrid是正确的,但不是我需要的:

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;
}

这不是我需要的,因为我正在做测试。如果我的数独是:

SudokuGrid actual = new SudokuGrid(2, 3);

那么我期望的数独就不可能只是:

SudokuGrid expected = new SudokuGrid(2, 3);

但应该是:

Field[,] expected = sudoku.Grid;

我不能用这个类来比较它的grid属性,因为setter是私有的,所以我不能设置grid。如果我必须改变我的原始代码,以便我的单元测试可以工作,这将是愚蠢的。

问题:

  • 那么它们是一种实际比较多维数组的方法吗?(所以我可以重写一个多维数组使用的相等方法吗?)
  • 有没有别的办法可以解决我的问题?

如何在相等上比较多维数组

您可以使用以下扩展方法,但是您必须使Field实现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;
}