[英]How to compare multidimensional arrays on equality?
我知道你可以使用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
构造函数中设置。 因此,所有这些属性都有私人制定者。 我想保持这种方式。
现在,我正在使用C#单元测试进行一些测试。 我想比较2个Grids
的价值,而不是他们的参考。
因为我通过构造函数使用私有setter设置所有内容。 类SudokuGrid
这个Equal覆盖是正确的,但不是我需要的:
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;
因此我无法使用该类来比较它的网格属性,因为我不能只设置网格,因为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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.