การวนซ้ำอย่างมีประสิทธิภาพผ่านอาร์เรย์ของจำนวนเต็มที่ไม่ทราบขนาดใน C # นั้นเป็นเรื่องง่าย มาดูกันว่าเป็นอย่างไร
ประการแรก ตั้งค่าอาร์เรย์ แต่อย่ากำหนดขนาด −
int[] arr = new int[] { 5, 7, 2, 4, 1 }; ตอนนี้ หาความยาวแล้ววนซ้ำในอาร์เรย์โดยใช้ for loop -
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