Csharp/CSharp Tutorial/Data Structure/Array Length

Материал из .Net Framework эксперт
Версия от 12:15, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Array sizes and dimensions.

using System;
class MainClass {
    public static void PrintArray(int[] arr) {
        for (int i = 0; i < arr.Length; ++i)
            Console.WriteLine("OneDArray Row {0} = {1}", i, arr[i]);
    }
    public static void PrintArrayRank(int[,] arr) {
        Console.WriteLine("PrintArrayRank: {0} dimensions", arr.Rank);
    }

    public static void Main() {
        int[] x = new int[10];
        for (int i = 0; i < 10; ++i)
            x[i] = i;
        PrintArray(x);
        int[,] y = new int[10, 20];
        for (int k = 0; k < 10; ++k)
            for (int i = 0; i < 20; ++i)
                y[k, i] = i * k;
        PrintArrayRank(y);
    }
}

Defining the Array Size at Runtime

class MainClass
{
  static void Main()
  {
    string[] groceryList;
    System.Console.Write("How many items on the list? ");
    int size = int.Parse(System.Console.ReadLine());
    groceryList = new string[size];
  }
}

Use the GetLength() method to get number of elements in each dimension of the two dimensional array

using System;
class MainClass
{
  public static void Main()
  {
    string[,] names = {
      {"J", "M", "P"},
      {"S", "E", "S"},
      {"C", "A", "W"},
      {"G", "P", "J"},
    };
    int numberOfRows = names.GetLength(0);
    int numberOfColumns = names.GetLength(1);
    Console.WriteLine("Number of rows = " + numberOfRows);
    Console.WriteLine("Number of columns = " + numberOfColumns);
  }
}
Number of rows = 4
Number of columns = 3

Use the Length array property

using System; 
 
class MainClass {  
  public static void Main() {  
    int[] nums = new int[10];  
 
    Console.WriteLine("Length of nums is " + nums.Length);  
  
    Console.Write("use Length to initialize nums");
    for(int i=0; i < nums.Length; i++)  
      nums[i] = i * i;  
  
    Console.Write("now use Length to display nums");
    Console.Write("Here is nums: "); 
    for(int i=0; i < nums.Length; i++)  
      Console.Write(nums[i] + " ");  
  }  
}
Length of nums is 10
use Length to initialize numsnow use Length to display numsHere is nums: 0 1 4 9 16 25 36 49 64 81 "

Use the Length array property on a 3-D array

using System; 
 
class MainClass {  
  public static void Main() {  
    int[,,] nums = new int[10, 5, 6];  
 
    Console.WriteLine("Length of nums is " + nums.Length);  
  
  }  
}
Length of nums is 300

Using Length - 1 in the Array Index

class MainClass
{
  static void Main()
  {
    string[] languages = new string[9];
    languages[4] = languages[languages.Length - 1];
  }
}