ข้อผิดพลาดนี้เกิดขึ้นเมื่อกำลังเรียกใช้กระบวนการวนซ้ำบนคอลเลกชัน (เช่น:รายการ) และคอลเลกชันถูกแก้ไข (เพิ่มหรือลบข้อมูล) ระหว่างรันไทม์
ตัวอย่าง
using System;
using System.Collections.Generic;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
try {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 0,
Name = "Jack"
},
new Student {
Id = 2,
Name = "Jack"
}
};
foreach (var student in studentsList) {
if (student.Id <= 0) {
studentsList.Remove(student);
}
else {
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
}
catch(Exception ex) {
Console.WriteLine($"Exception: {ex.Message}");
Console.ReadLine();
}
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
} ผลลัพธ์
ผลลัพธ์ของโค้ดด้านบนคือ
Id: 1, Name: John Exception: Collection was modified; enumeration operation may not execute.
ในตัวอย่างข้างต้น ลูป foreach ถูกดำเนินการบนรายชื่อนักเรียน เมื่อรหัสนักเรียนเป็น 0 รายการจะถูกลบออกจากรายชื่อนักเรียน เนื่องจากการเปลี่ยนแปลงนี้ studentList จึงได้รับการแก้ไข (ปรับขนาด) และมีการโยนข้อยกเว้นระหว่างรันไทม์
แก้ไขปัญหาข้างต้น
เพื่อแก้ปัญหาข้างต้น ให้ดำเนินการ ToList() ในรายชื่อนักเรียนก่อนเริ่มการวนซ้ำแต่ละครั้ง
foreach (var student in studentsList.ToList())
ตัวอย่าง
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 0,
Name = "Jack"
},
new Student {
Id = 2,
Name = "Jack"
}
};
foreach (var student in studentsList.ToList()) {
if (student.Id <= 0) {
studentsList.Remove(student);
}
else {
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
Console.ReadLine();
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
} ผลลัพธ์ของโค้ดด้านบนคือ
ผลลัพธ์
Id: 1, Name: John Id: 2, Name: Jack