System.IndexOutOfRangeException 尝试将数据从列表复制到二维数组时

System.IndexOutOfRangeException when trying to copy data from list to 2d array

我遇到异常:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

on col ++ 当它在第二个循环中时。我正在尝试将 list> 中的值放到 excel 列和行中。请让我知道我做错了什么。

object[,] cellValuesToWrite = new string[excelRange.Rows.Count, excelRange.Columns.Count];                
foreach (List<string> errorRecord in section.ErrorRecords)
{
    int rows = 0;
    int col = 0;
    int length = errorRecord.Count;
    foreach (var elem in errorRecord)
    {
        if (col < length)
        {
            cellValuesToWrite[rows, col] = elem;
            col++;
        }
    }
    rows++;
}

如果您使用 excelRange.Rows.Count 创建数组并且 excelRange.Rows.Count 为 5,则您无法访问 cellValuesToWrite[5, col],因为索引从 0 开始并且您尝试以这种方式访问​​第 6 个元素。

为什么不使用一个很好的旧 for 循环(特别是如果你需要索引):

for (int row = 0; row < cellValuesToWrite.GetLength(0); row++)
{
    for (int col = 0; col < cellValuesToWrite.GetLength(1); col++)
    {
        cellValuesToWrite[row, col] = section.ErrorRecords[row][col];
    }   
}