📜  c# length 2d array - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.225000             🧑  作者: Mango

C# Length of 2D Array

In C#, a 2D array is an array of arrays. It is essentially an array in which each element is itself an array. To find the length of a 2D array, we need to know the number of rows and the number of columns. We can use the GetLength() method to find the length of the first dimension and the GetLength() method with an argument of 1 to find the length of the second dimension.

Here is an example of how to find the length of a 2D array in C#:

int[,] myArray2D = new int[3, 5];
int rows = myArray2D.GetLength(0);
int columns = myArray2D.GetLength(1);

Console.WriteLine("Rows: " + rows);
Console.WriteLine("Columns: " + columns);

This code will create a 2D array with 3 rows and 5 columns. It then uses the GetLength() method with an argument of 0 to find the length of the first dimension, which is 3. It then uses the GetLength() method with an argument of 1 to find the length of the second dimension, which is 5.

Here is another example of how to find the length of a 2D array using a nested loop:

int[,] myArray2D = new int[3, 5];
int rows = myArray2D.GetLength(0);
int columns = myArray2D.GetLength(1);
int count = 0;

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        count++;
    }
}

Console.WriteLine("Length of 2D array: " + count);

This code will create a 2D array with 3 rows and 5 columns. It then uses a nested loop to iterate over all the elements in the array and increments a counter. The counter is then used to find the length of the 2D array, which is 15.

In conclusion, the length of a 2D array in C# can be found using the GetLength() method on each dimension separately, or by using a nested loop to iterate over all the elements in the array and counting them.