「Collection was modified; enumeration operation may not execute.」というエラーが出る時の解決方法について説明します。
広告
以下のようにforeachの中でListの内容を変更する処理をするとエラーが発生します。
foreach (var item in itemList) { if(item == removeItem) itemList.Remove(item); // InvalidOperationException: Collection was modified; enumeration operation may not execute. }
ToArray()で解決できます。ToArray()は、List
foreach (var item in itemList.ToArray()) { if(item == removeItem) itemList.Remove(item); }