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

C#ArraysMultidimensional Array

C# Problem Overview


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;

C# Solutions


Solution 1 - C#

matrix.GetLength(0)  -> Gets the first dimension size

matrix.GetLength(1)  -> Gets the second dimension size

Solution 2 - C#

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.

Solution 3 - C#

for 2-d array use this code :

var array = new int[,]
{
    {1,2,3,4,5,6,7,8,9,10 },
    {11,12,13,14,15,16,17,18,19,20 }
};
var row = array.GetLength(0);
var col = array.GetLength(1);

output of code is :

  • row = 2
  • col = 10

for n-d array syntax is like above code:

var d1 = array.GetLength(0);   // size of 1st dimension
var d2 = array.GetLength(1);   // size of 2nd dimension
var d3 = array.GetLength(2);   // size of 3rd dimension
.
.
.
var dn = array.GetLength(n-1);   // size of n dimension

Best Regards!

Solution 4 - C#

Use matrix.GetLowerBound(0) and matrix.GetUpperBound(0).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMuhammad FaisalView Question on Stackoverflow
Solution 1 - C#mindandmediaView Answer on Stackoverflow
Solution 2 - C#Nicholas CareyView Answer on Stackoverflow
Solution 3 - C#D.L.MANView Answer on Stackoverflow
Solution 4 - C#Matt TView Answer on Stackoverflow