简体   繁体   中英

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.

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

//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

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

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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