Collections, IEnumerable & IEnumerator (Part 1)This multi part tutorial is all Collections, IEnumerable and IEnumerator.
I'll cover IEnumerable & IEnumerator in Part 2, as what they are will take a little explaining.
Setup
A Form with a listbox and button.
CODE
Dim a As String() = {"a", "b", "c", "d", "e", "f", "g"}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListBox1.Items.AddRange(a)
End Sub
Removing Items from a collection.
Let do it using the ItemCODE
Private Sub But_Remove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles But_Remove.Click
For Each si In Me.ListBox1.SelectedItems
Me.ListBox1.Items.Remove(si)
Next
End Sub

QUOTE("Error Message")
List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.
Let do it using the IndicesCODE
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Int32 = 0 To Me.ListBox1.SelectedIndices.Count - 1
Me.ListBox1.Items.RemoveAt(Me.ListBox1.SelectedIndices(i))
Next
End Sub

QUOTE("Error Message")
Index was outside the bounds of the array.
A Solution but it's BackwardsCODE
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
For i As Int32 = Me.ListBox1.SelectedIndices.Count - 1 To 0 Step -1
Me.ListBox1.Items.RemoveAt(Me.ListBox1.SelectedIndices(i))
Next
End Sub
Why do I receive the above to errors with the first two but not in the third?To know why, you first have to understands what happens when you remove you remove an item.
The simple answer is your change the size of the array/collection. (More information on the first error in part 2)
Note: the code block is to preserve the whitespaceCODE
[ A ][ B ][ C ][ D ][ E ][ F ]
Suppose we remove want [ A ] and [ B ] or Indices {0,1}
CODE
[ B ][ C ][ D ][ E ][ F ]
What is the indice of element [ B ]? Is it same as before?
Answer: 0. No.
So lets see why do it in reverse works.
CODE
[ A ][ B ][ C ][ D ][ E ][ F ]
Suppose we remove want [ A ] and [ B ] or Indices {0,1}, remember we're doing this in reverse so [ B ][ A ] or {1,0}
CODE
[ A ][ B ][ C ][ D ][ E ][ F ]
So removing [ B ] we're left with
CODE
[ A ][ C ][ D ][ E ][ F ]
What is the indice of element [ A ]? Is it same as before?
Answer: 0. Yes.
The reason it works is simple the next index is always going to be within the bounds of the now resized (smaller) collection.
Coming up in Part 2:
IEnumerable and IEnumeratorEdit: Added in link to Part 2