What is the difference between Array.GetLength() and Array.Length?

前端 未结 5 1702
自闭症患者
自闭症患者 2020-12-13 08:51

How do you use the Array.GetLength function in C#?

What is the difference between the Length property and the GetLength functi

相关标签:
5条回答
  • 2020-12-13 09:31

    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

    0 讨论(0)
  • 2020-12-13 09:36

    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.

    0 讨论(0)
  • 2020-12-13 09:37

    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.

    0 讨论(0)
  • 2020-12-13 09:46

    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
    
    0 讨论(0)
  • 2020-12-13 09:48

    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.

    0 讨论(0)
提交回复
热议问题