You want to process all the items in a collection one at a time.
Sample code folder: Chapter 08\Collections
Use a For Each loop, or use the collection's Count property in a For…Next loop.
The For Each loop is the recommended way to process items in a collection because you don't need an index variable, you don't have to access the Count property of the collection, and each item in the collection is automatically retrieved (i.e., you don't have to explicitly access each indexed item).
The following code shows both a For…Next loop and a For Each loop used to access the same collection. Each loop creates a single line of the output display, showing the contents of each item in the collection:
Dim result As New System.Text.StringBuilder Dim numberCollection As New Collection ' ----- Start with a basic collection. numberCollection.Add(14, "C") numberCollection.Add(25, "D") numberCollection.Add(36, "E") numberCollection.Add(47, "A") numberCollection.Add(58, "B") ' ----- Scan the collection with a loop counter. ' Collections are base-1, not base-0. For counter As Integer = 1 To numberCollection.Count result.Append(numberCollection(counter)) result.Append(",") Next counter ' ----- Remove the ending comma. result.Length -= 1 result.AppendLine( ) ' ----- Scan the collection by item. For Each number As Integer In numberCollection result.Append(number) result.Append(",") Next number ' ----- Remove the ending comma. result.Length -= 1 result.AppendLine( ) ' ----- Retrieve items by key. result.Append(numberCollection("A")).Append(",") result.Append(numberCollection("B")).Append(",") result.Append(numberCollection("C")).Append(",") result.Append(numberCollection("D")).Append(",") result.Append(numberCollection("E")) ' ----- Display the results. MsgBox(result.ToString( ))
The third line of the output is the same collection accessed in the order of the item keys, instead of the default order, which is based on the item positions in the collection. Figure 8-20 shows the collection's items as accessed in each of these three ways.
Figure 8-20. Items in a collection can be accessed with For Next or For Each loops or by the item keys
Recipes 8.17, 8.18, through 8.19 show other features of collections.