ภาพรวม
ลูป foreach ใช้วนซ้ำผ่านทุกสมาชิกของคอลเลกชันที่ implement IEnumerable หรือ IEnumerable<T> ไวยากรณ์ง่ายและอ่านง่าย
ตัวอย่าง: วนซ้ำ LinkedList
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
LinkedList linkedList = new LinkedList();
linkedList.AddLast(25);
linkedList.AddLast(50);
linkedList.AddLast(100);
linkedList.AddLast(200);
linkedList.AddLast(400);
linkedList.AddLast(500);
linkedList.AddLast(550);
linkedList.AddLast(600);
linkedList.AddLast(800);
linkedList.AddLast(1200);
Console.WriteLine("Count of nodes = " + linkedList.Count);
foreach (int val in linkedList) {
Console.WriteLine(val);
}
Console.WriteLine("Does the LinkedList has node 800? " + linkedList.Contains(800));
}
}
ผลลัพธ์
Count of nodes = 10 25 50 100 200 400 500 550 600 800 1200 Does the LinkedList has node 800? True
สรุป
foreachอ่านอย่างเดียว ไม่สามารถแก้ไขคอลเลกชันขณะวนได้- ใช้กับอาร์เรย์, List, Dictionary, Set, LinkedList, และคอลเลกชันอื่นๆ
- ตัวแปรใน foreach เป็น read-only ภายในลูป