如何在 C# 中高效地迭代遍歷大小未知的整數陣列


要在 C# 中高效地迭代遍歷大小未知的整數陣列非常容易,我們來看看如何做。

首先,設定一個數組,但不要設定大小−

int[] arr = new int[] { 5, 7, 2, 4, 1 };

現在,獲取長度並使用 for 迴圈迭代遍歷一個數組 −

for (int i = 0; i< arr.Length; i++) {
   Console.WriteLine(arr[i]);
}

讓我們看一個完整的示例 −

示例

 線上演示

using System;

public class Program {
   public static void Main() {
      int[] arr = new int[] {
         5,
         7,
         2,
         4,
         1
      };

      // Length
      Console.WriteLine("Length:" + arr.Length);

      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine(arr[i]);
      }
   }
}

輸出

Length:5
5
7
2
4
1

更新時間:2020 年 6 月 22 日

406 次瀏覽

開啟你的 事業

完成課程認證

開始
廣告