如何在 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
廣告