How do you use the Array.GetLength
function in C#?
What is the开发者_StackOverflow中文版 difference between the Length
property and the GetLength
function?
GetLength
takes an integer that specifies the dimension of the array that you're querying and returns its length. Length
property returns the total number of items in an array:
int[,,] a = new int[10,11,12];
Console.WriteLine(a.Length); // 1320
Console.WriteLine(a.GetLength(0)); // 10
Console.WriteLine(a.GetLength(1)); // 11
Console.WriteLine(a.GetLength(2)); // 12
For 1-dimensional arrays Length
and GetLength(0)
are exactly the same.
For arrays of higher rank Length
is the product of all GetLength(0..Rank-1)
values, in other words it is always the total number of fields.
The .Length
property returns the number of elements in an array, whether it be one dimensional or multidimensional. That is a 2x6 array will have length of 12.
The .GetLength(0)
method returns number of elements in the row direction in a multidimensional array. For a 2x6 array that is 2.
The .GetLength(1)
method returns number of elements in the column direction in a multidimensional array. For a 2x6 array that is 6.
These do not return an actual element value, as stated by the chosen answer above.
GetLength returns the length of a specified dimension of a mulit-dimensional array.
Length returns the sum of the total number of elements in all the dimensions.
- For a single-dimensional array, Length == GetLength(0)
- For a two-dimensional array, Length == GetLength(0) * GetLength(1)
etc.
In mathematical term, we call as m rows and n columns, so the results is product of m*n for a two dimensional array. In this case GetLength(0) = m
rows and GetLength(1)= n
columns. For e.g see below example
string[,] stocks ={{"RELIND","Reliance Industries","1006.30"},{"TATMOB","Tata Mobiles","504.10"},{"ALST","Allstate","800.00"}, {"GE","GE Motors","810.00"}
};
The stocks arrays return GetLength(0)= 4
and GetLength(1)=3
and length =12
精彩评论