You cannot remove an object from the collection during enumeration. You cannot modify the collection at all. This will cause an error (the collection has been modified, the enumeration operation may not be performed). But you can add the objects you want to delete / delete in another collection:
Dim removeEnemies = New List(Of enemy) For Each enemy As enemy In lstEnemy ' ... ' If enemy.enemy.Left < 0 Then removeEnemies.Add(enemy.enemy) End If Next For Each enemy In removeEnemies lstEnemy.Remove(enemy) Me.Controls.Remove(enemy.enemy) Next
These methods will force the list to change its version (which is checked during enumeration):
- Add
- Clear
- Embed
- Insertrange
- Delete
- Removerange
- Removeat
- Reverse
- [indexer installer]
- Sorting
Another option is to use For-Loop and loop it back:
For i As Int32 = lstEnemy.Count - 1 To 0 Step -1 Dim enemy = lstEnemy(i) ' ... ' If enemy.enemy.Left < 0 Then lstEnemy.Remove(enemy) Me.Controls.Remove(enemy.enemy) End If Next
This will not result in this error, but is not readable like that. You need to go from list.Count - 1 To 0 , because you want to remove items that would have changed the Count property, and the index that was available before the item was deleted now raises an ArgumentOutOfRangeException .
Last but not least, you can use List.RemoveAll :
lstEnemy.RemoveAll(Function(enemy) enemy.enemy.Left < 0)
source share