📌  相关文章
📜  C#|数组中存在的元素总数

📅  最后修改于: 2021-05-29 13:25:30             🧑  作者: Mango

Array.GetLength(Int32)方法用于查找Array的指定维中存在的元素总数。

句法:

public int GetLength (int dimension);

此处,维度是需要确定长度的数组的从零开始的维度。

返回值:该方法的返回类型为System.Int32 。此方法返回一个32位整数,该整数表示指定维中的元素数。

异常:如果Dimension的值小于零或Dimension的值等于或大于Rrank,则此方法将提供IndexOutOfRangeException。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# program to illustrate the
// use of GetLength() method
using System;
  
public class GFG {
      
    // Main method
    static public void Main()
    {
  
        // create and initalize array
        int[] myarray = {445, 44, 66, 6666667, 78, 878, 1};
  
        // Display the array
        Console.WriteLine("The elements of myarray :");
          
        foreach(int i in myarray)
        {
            Console.WriteLine(i);
        }
  
        // Find the number of element in myarray
        int result = myarray.GetLength(0);
        Console.WriteLine("Total Elements: {0}", result);
    }
}
输出:
The elements of myarray :
445
44
66
6666667
78
878
1
Total Elements: 7

范例2:

// C# program to check arrays contain
// same number of elements or not
using System;
  
public class GFG {
      
    // Main method
    static public void Main()
    {
  
        // create and initalizing array
        int[] myarray1 = {100, 0, 400, 660, 700, 809, 0};
        int[] myarray2 = {100, 0, 400, 660, 700};
        int[] myarray3 = {100, 0, 400, 660, 700, 809, 0};
  
        // Find the number of element in myarray
        // using GetLength() method
        int result1 = myarray1.GetLength(0);
        int result2 = myarray2.GetLength(0);
        int result3 = myarray3.GetLength(0);
  
        // Check if myarray1, myarray2, myarray3 
        // contain the same number of elements or not
        Console.WriteLine("myarray1 and myarray2: {0}", 
                             Equals(result1, result2));
                               
        Console.WriteLine("myarray1 and myarray3: {0}",
                             Equals(result1, result3));
    }
}
输出:
myarray1 and myarray2: False
myarray1 and myarray3: True

参考: https://docs.microsoft.com/zh-cn/dotnet/api/system.array.getlength?view=netcore-2.1