中級 › Collection was modified の原因と直し方 › パターン3
Collection was modified の原因と直し方
foreach中にList等のコレクションの要素数を変えると発生します。
1 class Program { 2 static void Main(string[] args) { 3 var nums = new System.Collections.Generic.List<int> { 1, 2, 3 }; 4 foreach (int n in nums) { 5 if (n == 3) { 6 _________________________________; ^ 7 } 8 } 9 } 10 }
Unhandled exception. System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at Program.Main(String[] args) in Program.cs:line 4
空欄を埋めてビルドを通す
RemoveAtでインデックス指定で消す場合も同様です。安全に消したいならToList()でコピーしてから反復します。
次の問題