for each loop คล้ายกับ for loop; อย่างไรก็ตาม การวนซ้ำจะดำเนินการสำหรับแต่ละองค์ประกอบในอาร์เรย์หรือกลุ่ม ดังนั้น ดัชนีจึงไม่อยู่ใน foreach loop
เรามาดูตัวอย่าง Bubble Sort ซึ่งหลังจากจัดเรียง Element แล้ว เราจะแสดง Element โดยใช้ Foreach Loop
foreach (int p in arr) Console.Write(p + " ");
ต่อไปนี้เป็นตัวอย่างที่สมบูรณ์
ตัวอย่าง
using System;
namespace BubbleSort {
class MySort {
static void Main(string[] args) {
int[] arr = { 78, 55, 45, 98, 13 };
int temp;
for (int j = 0; j <= arr.Length - 2; j++) {
for (int i = 0; i <= arr.Length - 2; i++) {
if (arr[i] > arr[i + 1]) {
temp= arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
Console.WriteLine("Sorted:");
foreach (int p in arr)
Console.Write(p + " ");
Console.Read();
}
}
} ผลลัพธ์
Sorted: 13 45 55 78 98