How to get the length of row/column of multidimensional array in C#?
Solution 1:
matrix.GetLength(0) -> Gets the first dimension size
matrix.GetLength(1) -> Gets the second dimension size
Solution 2:
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.