如何在C#中查找数组的排名

2021年3月13日17:18:33 发表评论 870 次浏览

Array.Rank属性用于获得排名Array。等级是数组的维数。例如, 一维数组返回1, 二维数组返回2, 依此类推。

语法如下:

public int Rank { get; }

适当的价值:它返回类型Array的等级(维数)System.Int32.

下面的程序说明了上面讨论的属性的用法:

范例1:

// C# program to illustrate the
// Array.Rank Property
using System;
namespace lsbin {
  
class GFG {
  
     // Main Method
     public static void Main()
     {
  
         // declares a 1D Array of string.
         string [] weekDays;
  
         // allocating memory for days.
         weekDays = new string [] { "Sun" , "Mon" , "Tue" , "Wed" , "Thu" , "Fri" , "Sat" };
  
         // using Rank Property
         Console.WriteLine( "Dimension of weekDays array: " 
                                        + weekDays.Rank);
     }
}
}

输出如下:

Dimension of weekDays array: 1

范例2:

// C# program to illustrate the
// Array.Rank Property
using System;
namespace lsbin {
  
class GFG {
  
     // Main Method
     public static void Main()
     {
  
         // declaring an 2-D array
         int [, ] arr2d = new int [4, 2];
  
         // declaring an 3-D array
         int [, , ] arr3d = new int [4, 2, 3];
  
         // declaring an jagged array
         int [][] jdarr = new int [2][];
  
         // using Rank Property
         Console.WriteLine( "Dimension of arr2d array: " 
                                         + arr2d.Rank);
  
         Console.WriteLine( "Dimension of arr3d array: " 
                                         + arr3d.Rank);
  
         // for the jagged array it 
         // will always return 1
         Console.WriteLine( "Dimension of jdarr array: " 
                                         + jdarr.Rank);
     }
}
}

输出如下:

Dimension of arr2d array: 2
Dimension of arr3d array: 3
Dimension of jdarr array: 1

注意:

  • 一种锯齿状数组(数组的数组)是一维数组, 因此其Rank属性的值为1。
  • 检索此属性的值是O(1)操作。

参考:

  • https://docs.microsoft.com/en-us/dotnet/api/system.array.rank?view=netframework-4.7.2

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: