简体   繁体   English

如何在c#中找到两个二维数组之间的差异

[英]How to find the difference between two 2D arrays in c#

I've two excel files and I want to extract the difference between them to put in another excel file.我有两个 excel 文件,我想提取它们之间的差异以放入另一个 excel 文件。

To find the difference I am using a specific reference column from each file to compare.为了找到差异,我使用每个文件中的特定参考列进行比较。

Using the NPOI library, I stored the data from each excel in two 2d arrays and I was able to find the difference between the two by putting the references columns in unidimensional array and comparing them like below使用 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);

To copy the difference to a new file I was trying to first put it in a third 2d array and then write in an excel but I am having a hard time getting the difference to the third 2d array要将差异复制到新文件中,我试图首先将其放入第三个二维数组中,然后在 excel 中写入,但我很难将差异复制到第三个二维数组中

I tried the below我尝试了以下

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 keep getting Index Out of bounds O 不断让索引越界

There is no need to copy data to 1D arrays, just write a double loop that iterates over both dimensions.无需将数据复制到一维数组,只需编写一个在两个维度上迭代的双循环。 For example assuming you have two 2D arrays , a and b :例如,假设您有两个二维数组ab

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

This produces an bool-array with the only the overlapping parts of the two matrices, and mark if the values are different or not.这会产生一个布尔数组,其中只有两个矩阵的重叠部分,并标记值是否不同。 It should be trivial to change it to return one or the other of the values if they are different.如果它们不同,更改它以返回一个或另一个值应该是微不足道的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM