C#二维int数组,Sum off所有元素

aki*_*nov 2 c# arrays

我试图制作一个程序,它总结了数组中的元素.但我在MVS上有' System.IndexOutOfRangeException '错误.谁能说出我的错误在哪里?

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

static void Main(string[] args)
{
    int[,] arr = { { 1, 3 }, { 0, -11 } };
    int total = Sum(arr);

    Console.WriteLine(total);
    Console.ReadKey(); 
}
Run Code Online (Sandbox Code Playgroud)

juh*_*arr 6

你必须得到每个维度的长度(Length2D数组的属性是数组中的项目总数),比较应该是<,而不是<=

for (int i = 0; i < arr.GetLength(0); i++)
{
    for (int j = 0; j < arr.GetLength(1); j++)
    {
         total += arr[i,j];
    }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用一个foreach循环

foreach (int item in arr)
{
    total += item;
}
Run Code Online (Sandbox Code Playgroud)

甚至是Linq

int total = arr.Cast<int>().Sum();
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nko 5

试试Linq

  int[,] arr = { { 1, 3 }, { 0, -11 } };

  int total = arr.OfType<int>().Sum();
Run Code Online (Sandbox Code Playgroud)

非Linq解决方案:

  int total = 0;

  foreach (var item in arr)
    total += item;
Run Code Online (Sandbox Code Playgroud)