如何在C#中获取多维数组的行/列长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9404683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the length of row/column of multidimensional array in C#?
提问by Muhammad Faisal
How do I get the length of a row or column of a multidimensional array in C#?
如何在 C# 中获取多维数组的行或列的长度?
for example:
例如:
int[,] matrix = new int[2,3];
matrix.rowLength = 2;
matrix.colLength = 3;
采纳答案by mindandmedia
matrix.GetLength(0) -> Gets the first dimension size
matrix.GetLength(1) -> Gets the second dimension size
回答by Matt T
Use matrix.GetLowerBound(0)and matrix.GetUpperBound(0).
使用matrix.GetLowerBound(0)和matrix.GetUpperBound(0)。
回答by Nicholas Carey
Have you looked at the properties of an Array?
你看过 a 的属性Array吗?
Lengthgives 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.
Length为您提供数组的长度(单元格总数)。GetLength(n)为您提供指定维度中的单元格数(相对于 0)。如果您有一个 3 维数组:int[,,] multiDimensionalArray = new int[21,72,103] ;那么
multiDimensionalArray.GetLength(n)对于 n = 0、1 和 2,将分别返回 21、72 和 103。
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.
如果您正在构建锯齿状/稀疏数组,那么问题会更复杂一些。锯齿状/稀疏数组 [通常] 构造为数组中数组的嵌套集合。在这种情况下,您需要依次检查每个元素。这些通常是嵌套的一维数组,但没有理由不能拥有包含包含 5d 数组的 3d 数组的 2d 数组。
In any case, with a jagged/sparse structure, you need to use the length properties on each cell.
在任何情况下,对于锯齿状/稀疏结构,您都需要在每个单元格上使用长度属性。
回答by D.L.MAN
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
- 行 = 2
- 列 = 10
for n-d array syntax is like above code:
for nd 数组语法就像上面的代码:
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!
此致!

