在 C# 中求和锯齿状的 int 数组

Summing a jagged int array in C#

如此处所做:,但这次使用锯齿状数组。得到:

System.IndexOutOfRangeException.

我是初学者,求助。这是我的代码:

public static int Sum(int[][] arr) 
{
    int total = 0;
    for (int i = 0; i < arr.GetLength(0); i++)
    {
         for (int j = 0; j < arr.GetLength(1); j++) 
         { 
              total += arr[i][j];
         }
    } 
    return total; 
}

static void Main(string[] args)
{
     int[][] arr = new int[][] 
     {
          new int [] {1},
          new int [] {1,3,-5},
     };
     int total = Sum(arr);
     Console.WriteLine();
     Console.ReadKey();    
}

在你的内部循环中改为这样做:

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i] != null)
    {
        for (int j = 0; j < arr[i].Length; j++) 
        { 
            total += arr[i][j];
        }  
    }
} 
return total; 

因为您的列表甚至都没有,所以您在 arr.GetLength(1) 上得到了第一个维度的异常 - 它在那个地方没有项目。

如果数组看起来像这样,则需要 if (arr[i] != null) 行:

 int[][] arr = new int[][] 
 {
      new int [] {1},
      null,
      new int [] {1,3,-5},
 };

在这种情况下,当我们使用 i==1 循环并尝试执行 arr[i].Length (意思是 arr[1].Length 我们将收到 NullReferenceException.


在完成基础知识并使用 Linq 之后,您当前的所有 Sum 方法都可以替换为:

arr.SelectMany(item => item).Sum()

但最好从基础开始:)

由于您使用的是锯齿状数组,因此该数组的维度不一定是均匀的。看看那个锯齿状数组的初始化代码:

int[][] arr = new int[][] {
    new int [] {1},
    new int [] {1,3,-5},
};

所以在第一个维度中,有两个元素({1}{1, 3, -5})。但是第二维的长度不同。第一个元素只有一个元素 ({1}) 而第二个元素有 3 个元素 ({1, 3, -5})。 这就是为什么你要面对 IndexOutOfRangeException.

要解决此问题,您必须将内部循环调整为该维度的元素数。你可以这样做:

for (int i = 0; i < arr.Length; i++) {
    for (int j = 0; j < arr[i].Length; j++) { 
        total += arr[i][j];
    }  
}