You need to delete an item from a collection.
Sample code folder: Chapter 08\Collections
Use the collection's Remove() method, passing either the position of the item or its key string.
The following example fills a collection with several words using "key strings," identifiers that provide an optional way to specify each item. The item at index position 5 is then removed, followed by the item with key "six":
Dim result As New System.Text.StringBuilder Dim wordCollection As New Collection ' ----- Start with a basic collection. wordCollection.Add("This", "one") wordCollection.Add("is", "two") wordCollection.Add("a", "three") wordCollection.Add("collection", "four") wordCollection.Add("of", "five") wordCollection.Add("words", "six") ' ----- Remove an element by position. wordCollection.Remove(5) ' ----- Remove an element by key. wordCollection.Remove("six") ' ----- Dipslay the collection. For Each word As String In wordCollection result.Append(word) result.Append(Space(1)) Next word MsgBox(result.ToString( ))
Once item number 5 is removed, the item at position 6 moves to position 5. This means that removing items 5 and 6 both by number wouldn't work; you would need to remove the item at position 5 twice in a row. This hints at the usefulness of using key strings to uniquely identify each item, especially when items might be freely added to or removed from the collection over time. Figure 8-19 shows the contents of the collection after the two items are removed.
Figure 8-19. The Remove( ) method removes items from a collection by position or by key
Recipes 8.17, 8.18, and 8.20 show other features of collections.