Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of row/column of multidimensional array in C#?

How do I get the length of a row or column of a multidimensional array in C#?

for example:

int[,] matrix = new int[2,3];  matrix.rowLength = 2; matrix.colLength = 3; 
like image 500
Muhammad Faisal Avatar asked Feb 22 '12 23:02

Muhammad Faisal


People also ask

How do you find the length of a row in a 2D array?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

What is the size of multidimensional array?

Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.

What is the formula to calculate size of a 2D array?

The size of a two dimensional array is equal to the multiplication of number of rows and the number of columns present in the array.


2 Answers

matrix.GetLength(0)  -> Gets the first dimension size  matrix.GetLength(1)  -> Gets the second dimension size 
like image 129
mindandmedia Avatar answered Oct 24 '22 11:10

mindandmedia


Have you looked at the properties of an Array?

  • Length gives you the length of the array (total number of cells).
  • GetLength(n) gives you the number of cells in the specified dimension (relative to 0). If you have a 3-dimensional array:

    int[,,] multiDimensionalArray = new int[21,72,103] ; 

    then multiDimensionalArray.GetLength(n) will, for n = 0, 1 and 2, return 21, 72 and 103 respectively.

If you're constructing Jagged/sparse arrays, then the problem is somewhat more complicated. Jagged/sparse arrays are [usually] constructed as a nested collection of arrays within arrays. In which case you need to examine each element in turn. These are usually nested 1-dimensional arrays, but there is not reason you couldn't have, say, a 2d array containing 3d arrays containing 5d arrays.

In any case, with a jagged/sparse structure, you need to use the length properties on each cell.

like image 37
Nicholas Carey Avatar answered Oct 24 '22 11:10

Nicholas Carey