簡體   English   中英

如何在c#中找到兩個二維數組之間的差異

[英]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 不斷讓索引越界

無需將數據復制到一維數組,只需編寫一個在兩個維度上迭代的雙循環。 例如,假設您有兩個二維數組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;
        }
    }
}

這會產生一個布爾數組,其中只有兩個矩陣的重疊部分,並標記值是否不同。 如果它們不同,更改它以返回一個或另一個值應該是微不足道的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM