Collections VB Help

Arrays are convenient for storing related data, but accessing individual elements can be a problem. To print the temperature in Atlanta, for instance, you would have to know the index that corresponds to Atlanta. If you didn’t, you would have to scan each element in the array until you found Atlanta. Ideally, arrays should be’ accessed by their contents. For example, you should be able to look up the temperature in Atlanta with a statement such as:

Temperatures(“Atlanta”)

In the. past, programmers had to resort to creative programming techniques to manipulate array data. Visual Basic provides an alternative: collections. Similar to an array, a collection stores related items, in this case, objects that have properties and methods. The advantage of a collection over an array is that the collection lets you access. its items via a key. If a city name is the key in the Temperatures() array, you can recall the temperature in Atlanta instantly by providing the-following key:

The Item argument is a method of the collection object that returns a collection item based on its key or index. Or, if you know the index of Atlanta’s entry in the collection, you can use a statement like:

MsgBox ‘The temperature in Atlanta is ‘ & Temperatures.ltem(6)

Of course, if you’re going to access a collection’s item with its index, there’s no advantage to using collections over arrays.

To use a collection, you must first declare ‘a collection variable, as follows:

Dim Temperatures As New Collection

The keyword New tells Visual Basic to create a new collection and name it Temperatures.

The collection object provides three methods and one property:

Add method Adds items to the collection

Remove method Deletes an item from the collection by index or key

Remove method Deletes an item from the collection by index or key

Count property Returns the number of items in the collection

Let’s look at each of these members in detail

Adding to a Collection

The Add method adds new items to the collection and it has the following syntax:

collection. Add value, key, before, after

To add a new element to a collection, assign its value to the item argument and its key to the key argument. To place the new item in a specific location in the array, specify one of the arguments before or after (but not both). To insert the new item before a specific element whose key (or index) you will specify, use the before argument. To place the new item after; an item, specify this item’s key or index with the after argument.

for example. add the temperature for the city of San Francisco to the Temperature collection, use the following statement:

Temperatures’.Add 78, ‘San Francisco’

The number 78 is the value to be stored (temperature), and the string “San Francisco” is the new item’s key. To insert this temperature immediately after the temperature of Santa Barbara, use the following statement:

Temperatures.Add 78, ‘San Francisco’, , ‘Santa Barbara’

the extra comma denotes the lack of the before argument. The Add method supports named arguments, so the previous statement could also be written as:

Collections aren’t sorted, nor do they have a method to automatically sort their items. To maintain an ordered collection of objects, use the before and after arguments. In most practical situations, however, you won’t care about sorting a collection’s items. You sort arrays to simplify access to their elements: you don’t have to do anything special to access the elements of collections,

Removing an Item from a Collection

The Remove method removes an item from a collection. The index argument can be either the position of the item you want to delete or the item’s key. To remove the city of Atlanta from your collection of temperatures, use the following statement:

Temperatures.Remove ‘Atlanta’

Or, if you know the city’s order in the collection, specify the index in place of the key:

Temperatures.Remove 6

Returning Items in a Collection

The Item method returns the value of an item in the collection. As with the Remove method, the index can be either the item’s position in the collection or its key. To recall the temperature in Atlanta , use one of the following statements: ‘

Tl = Temperatures.ltem(‘Atlanta’)
Tl = Temperatures.ltem(3)

The Item method is the default method for a collection object, so you can omit it when’ you access an item in a collection. The previous example could also be written as:

Tl a Temperatures(‘Atlanta’)

Counting a Collection

The Count property returns the number of items in the collection. To find out how many cities have been entered so far in the Temperatures collection, use the following statement:

Temperatures. Count

You can also use the Count property to scan all the elements of the collection, with a For Next loop such as the following:

Actually, a better way to scan the elements of a collection is the For Each … Next structure explained next.

Processing a Collection’s Items

To scan all the items in a Collection, Visual Basic provides the For Each … Next structure. Its syntax is as follows:

For Each item in Collection
{process item}
Next

The item variable is the loop counter, but you don’t have to initialize it or declare its type. The For Each statement scans all the items in the collection automatically and at each iteration the item variable assumes the current item’s value.

Using Collections

Let’s implement a collection for storing city names and temperatures. Start a new. project and add the following declaration in the Form:

Dim Temperatures As New Collection

This statement creates a new collection and names it Temperatures. Then enter the following code in the Form’s Load event:

Of course, you can add as many lines as you wish, read the data from a disk file, or prompt the user to enter city names and temperatures at runtime. New items can be added to the collection at any time.

Next, create a Command button, set its Caption property to “Show City Temperature”, and enter the following code in its Click subroutine:

This subroutine prompts users to enter the name of the city whose temperature they want to find. The program then recalls the value of the collection’s item, whose key is the city name supplied by the user. If the supplied key doesn’t exist, a runtime error is generated, which is why we ‘use the On Error statement. If the user enters a nonexistent city name, a runtime error is generated; Visual Basic intercepts it and executes the statements following the label No ltem.If the key exists in the array, then the temperature of the corresponding city’is displayed in a message box. ,

,
Finally, add another Command button to the Form, set its caption to Show Average Temperature, and enter the following code behind its Click event.

The Print statement displays each element in the Immediate window. The name of the loop ..variable is city, which refers to the value of the current item, not the city name. In this case, it’s the temperature in the current city. The counter of the For Each loop in the previous example could be named city, temp, or Boo.