Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You cannot delete an object from a collection during enumeration. You cannot modify the collection at all. That will cause an error(<em>Collection was modified; enumeration operation may not execute</em>). But you could add the objects that you want to delete/remove to another collection:</p> <pre><code>Dim removeEnemies = New List(Of enemy) For Each enemy As enemy In lstEnemy ' ... ' If enemy.enemy.Left &lt; 0 Then removeEnemies.Add(enemy.enemy) End If Next For Each enemy In removeEnemies lstEnemy.Remove(enemy) Me.Controls.Remove(enemy.enemy) Next </code></pre> <p>These methods will cause a list to change it's version(which is checked during enumeration):</p> <ul> <li>Add</li> <li>Clear</li> <li>Insert</li> <li>InsertRange</li> <li>Remove</li> <li>RemoveRange</li> <li>RemoveAt</li> <li>Reverse</li> <li>[the Indexer setter]</li> <li>Sort</li> </ul> <p>Another option is to use a <code>For-Loop</code> and loop it backwards:</p> <pre><code> For i As Int32 = lstEnemy.Count - 1 To 0 Step -1 Dim enemy = lstEnemy(i) ' ... ' If enemy.enemy.Left &lt; 0 Then lstEnemy.Remove(enemy) Me.Controls.Remove(enemy.enemy) End If Next </code></pre> <p>This will not raise that error but it's not as readable. You need to go from <code>list.Count - 1</code> To <code>0</code> because you want to remove items which would change the <code>Count</code> property and an index that was available before the item was removed causes now an <code>ArgumentOutOfRangeException</code>.</p> <p>Last but not least, you can use <a href="http://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx" rel="noreferrer"><code>List.RemoveAll</code></a>:</p> <pre><code>lstEnemy.RemoveAll(Function(enemy) enemy.enemy.Left &lt; 0) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload