Error เกิดเมื่อ **Modify Collection (Add/Remove) ขณะกำลัง Iterate ด้วย foreach**
โค้ดที่ผิด
var list = new List{ new Student {Id=1}, new Student {Id=0}, new Student {Id=2} }; foreach (var s in list) { if (s.Id <= 0) list.Remove(s); // ❌ Modify ในขณะ Iterate }
Output:
Id: 1, Name: John Exception: Collection was modified; enumeration operation may not execute.
วิธีแก้: ใช้ .ToList() สร้าง Copy ก่อน Iterate
foreach (var s in list.ToList()) // ✅ Iterate บน Copy
{
if (s.Id <= 0) list.Remove(s); // Safe
}
Output หลังแก้
Id: 1, Name: John Id: 2, Name: Jack
วิธีอื่นๆ
- for loop ถอยหลัง:
for (int i = list.Count - 1; i >= 0; i--)ลบได้ปลอดภัย - List.RemoveAll:
list.RemoveAll(s => s.Id <= 0);(Best Performance) - LINQ Where:
var newList = list.Where(s => s.Id > 0).ToList();(Immutable Approach)