[英]Find the difference between two 1d arrays to form a 2d array of those differences in the shortest time
[英]How to find the difference between two 2D arrays in c#
我有两个 excel 文件,我想提取它们之间的差异以放入另一个 excel 文件。
为了找到差异,我使用每个文件中的特定参考列进行比较。
使用 NPOI 库,我将每个 excel 的数据存储在两个二维数组中,我能够通过将引用列放在一维数组中并像下面这样比较它们来找到两者之间的差异
//copying the values in the references columns to unidimensional arrays
for (int j = 0; j<firstArray.length; j++)
firstArray[j] = firstArray2d[j, 8];
for (int j = 0; j<secondArray.length; j++)
secondArray[j] = secondArray2d[j, 8];
//below I extract the difference between the unidimensional arrays
IEnumerable<string> firstArrayOnly = firstArray.Except(secondArray);
要将差异复制到新文件中,我试图首先将其放入第三个二维数组中,然后在 excel 中写入,但我很难将差异复制到第三个二维数组中
我尝试了以下
string [] diff = new string[firstArrayOnly.Count()];
int cont = 0;
foreach (var n in firstArrayOnly)
{
diff[cont]=n;
cont++;
}
//until here works fine, the problem comes below
string[,] data = new string [firstArrayOnly.Count(),9];
for (int j = 0; j < firstArray2d.GetLength(0); j++)
{
string aux = diff[j];
if (firstArray2d[i,8] == aux)
for (int x = 0; x < firstArray2dGetLength(1); x++)
data[i,x] = firstArray2d[i,j];
}
O 不断让索引越界
无需将数据复制到一维数组,只需编写一个在两个维度上迭代的双循环。 例如,假设您有两个二维数组a
和b
:
var l0 = Math.Min(a.GetLength(0), b.GetLength(0));
var l1 = Math.Min(a.GetLength(1), b.GetLength(1));
var diff = new bool[l0, l1];
for (int i0 = 0; i0 < l0; i0++)
{
for (int i1 = 0; i1 < l1; i1++)
{
if (!a[i0, i1].Equals(b[i0, i1]))
{
diff[i0, i1] = true;
}
}
}
这会产生一个布尔数组,其中只有两个矩阵的重叠部分,并标记值是否不同。 如果它们不同,更改它以返回一个或另一个值应该是微不足道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.