Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))

4.6. Collections

Visual Basic defines an associative array object called a collection. Although similar to an array in that elements appear in a specific order, a collection stores its elements as key-value pairs. Once in a collection, each element can be retrieved by position, by key, or by iterating through the collection one element at a time.

Five of the Collection class's members are especially useful.

Add Method

Adds an item to the collection. Along with the data itself, you can specify an optional key by which the member can be referenced.

Clear Method

Removes all elements from the collection.

Count Property

Returns the number of elements in the collection.

Item Property

Retrieves an element from the collection either by its index (or ordinal position in the collection) or by its key (if provided when the element was added).

Remove Method

Deletes an element from the collection using the element's index or key.

The following code defines a collection of state names, using the state abbreviation as the key.

Dim states As New Collection states.Add("New York", "NY") states.Add("Michigan", "MI")

The elements of this collection can then be iterated using the For Each...Next construct.

Dim oneState As String For Each oneState In states MsgBox(oneState) Next oneState

Like arrays, collection members are accessible by their index value. The lower bound of a collection is always one (1).

New in 2005. The 2005 release of Visual Basic includes a new generics feature that allows collection (and other class) instances to be tied to a specific data type. See Chapter 10 for details on using this new feature.

Категории