dyl*_*ert 5 c# compare equals multidimensional-array
我知道你可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
所有这些属性都在SudokuGrid
构造函数中设置.因此,所有这些属性都有私人制定者.我想保持这种方式.
现在,我正在使用C#单元测试进行一些测试.我想比较Grids
他们的价值2 ,而不是他们的参考.
因为我通过构造函数使用私有setter设置所有内容.类中的Equal覆盖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;
}
Run Code Online (Sandbox Code Playgroud)
由于我正在进行测试,这不是我需要的.所以,如果我的实际数据是:
SudokuGrid actual = new SudokuGrid(2, 3);
Run Code Online (Sandbox Code Playgroud)
那么我期望的数独不仅仅是:
SudokuGrid expected = new SudokuGrid(2, 3);
Run Code Online (Sandbox Code Playgroud)
但应该是:
Field[,] expected = sudoku.Grid;
Run Code Online (Sandbox Code Playgroud)
因此我无法使用该类来比较它的网格属性,因为我不能只设置网格,因为setter是私有的.如果我不得不改变原始代码,那么我的单元测试就可以工作,那将是愚蠢的.
问题:
您可以使用以下扩展方法,但您必须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;
}
Run Code Online (Sandbox Code Playgroud)