[C#] 「Collection was modified; enumeration operation may not execute.」というエラーが出る時の解決方法

Unity

「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);
}

広告