컬렉션(예:목록)에서 루프 프로세스가 실행 중이고 런타임 중에 컬렉션이 수정(데이터 추가 또는 제거)될 때 이 오류가 발생합니다.
예시
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 루프는 StudentsList에서 실행됩니다. 학생의 ID가 0인 경우 해당 항목은 StudentsList에서 제거됩니다. 이 변경으로 인해 StudentsList가 수정(크기 조정)되고 런타임 중에 예외가 발생합니다.
위 문제 수정
위의 문제를 극복하려면 각 반복을 시작하기 전에 StudentsList에서 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