C#
C# / 배열(List) 비교해서 중복 안되는 항목 출력 / Collection was modified; enumeration operation may not execute
캬옹냐옹
2021. 3. 29. 13:43
728x90
//서버에서 삭제된 세차기 flaMain에서 삭제
List<string> list = new List<string>();
List<string> list2 = new List<string>();
//flpMain 에 등록된 세차기, 서버에 등록된 세차기 리스트에 대입
foreach (CarWash_Info_Card carWash_Info_Card in flpMain.Controls) list.Add(carWash_Info_Card.Name);
foreach (DocumentSnapshot documentSnapshot in allQuerySnapshot.Documents) list2.Add(documentSnapshot.Id);
//flpMain, 서버 등록된 세차기 비교 해서 중복되지 않는 항목 반환
var carWashExcept = carWash_Info_Card_List.Except(documentSnapshot_List);
//서버에 등록 안된 세차기 삭제
this.BeginInvoke((System.Action)(() =>
{
foreach (var item in carWashExcept.ToList()) //ToList 안붙여주면 에러 남, 중복 안되는 항목 반복문
{
foreach (CarWash_Info_Card carWash_Info_Card in flpMain.Controls) //flpMain에 등록된 것 중에 비교
{
if (carWash_Info_Card.Name == item) //중복 안된 항목과 같으면 삭제
{
flpMain.Controls.Remove(carWash_Info_Card);
rtbErorrStatus.AppendText($"carWashRemove: {carWash_Info_Card.Name} \r\n");
}
}
}
}));
Except() 는 Interesect() 연산의 반대 개념인 같지 않은 것을 반환 한다.
carWash_Info_Card_List.Except(documentSnapshot_List); 반환 된 값을 foreach 돌리면
'Collection was modified; enumeration operation may not execute' 에러가 난다.
이때, .Tolist()를 추가 하면 에러가 해결 된다.
아래 링크에 왜 에러가 나고 이렇게 사용 해야 하는지 나와있다.
stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute
Collection was modified; enumeration operation may not execute
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur. Collection was modified; enumeration operation may not execute Below is the code. This i...
stackoverflow.com
728x90