在 C # 中如何得到多维数组的行/列长度?

如何在 C # 中得到一个多维数组的行或列的长度?

例如:

int[,] matrix = new int[2,3];


matrix.rowLength = 2;
matrix.colLength = 3;
115378 次浏览
matrix.GetLength(0)  -> Gets the first dimension size


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

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

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.

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!

You can also use: matrix.GetUpperBound(0);//rows matrix.GetUpperBound(1);//columns