You want a simple example of a collection to demonstrate the basics of using the collection object.
Sample code folder: Chapter 08\ Collections
This recipe provides a simple example collection to use as a starting point for further explorations of the topic.
Collections provide capabilities similar to those of arrays, but they have some advantages. A collection is inherently more dynamic and allows the insertion and deletion of items, and it can be resized without loss of any current contents. You can do these same tasks with arrays, but collections make the whole process much simpler and more straightforward.
The following example creates a collection of strings. Each string(in this case they are all just simple words) is added to the collection using the collection's Add() method. After all words are added to the collection, its entire contents are retrieved for display and review, as shown in Figure 8-17:
Dim result As New System.Text.StringBuilder Dim wordCollection As New Collection ' ----- Build the collection. wordCollection.Add("This") wordCollection.Add("is") wordCollection.Add("a") wordCollection.Add("collection") wordCollection.Add("of") wordCollection.Add("words") ' ----- Display the collection. For Each word As String In wordCollection result.Append(word) result.Append(Space(1)) Next word MsgBox(result.ToString( ))
Figure 8-17. A collection of strings
As with arrays, you can retrieve each item from the collection using an index, or you can use the For Each loop, as shown in this example. Unlike with arrays, however, you can optionally pass a key string to the Add() method to provide a way to retrieve items from a collection based on their keys.
You can store varying types of data in the same collection. This provides some flexibility, but in most cases you should store only the same type of data in any single collection. Methods you write to process the collection's data will need to handle whatever data type is stored in the collection, so keeping it consistent greatly simplifies the coding requirements.
If data-type issues become a problem with your collections, consider using the new generic collections instead.
Recipes 8.18, 8.19, through 8.20 show other features of collections.