Each Collection object includes properties and methods you can use to insert, delete, and retrieve the items in the collection. The following table lists these items.
For information about |
See |
Adding items to the collection |
Add Method |
Returning the number of items in the collection |
Count Property |
Returning an item, by index or by key |
Item Property |
Deleting an item from the collection, by index or by key |
Remove Method |
These properties and methods provide only the most basic services for collections. For example, the Add method cannot check the type of object being added to a collection, which you might want to do to ensure that the collection contains only one kind of object. You can provide more robust functionality - and additional properties, methods, and events - by creating your own collection class, as described in the walkthrough, Walkthrough: Creating Your Own Collection Class.
The basic services of adding, deleting, and retrieving from a collection depend on keys and indexes. A key is a String value. It could be a name, a driver's license number, a social security number, or simply an integer converted to a string. The Add method allows you to associate a key with an item, as described in Adding, Deleting, and Retrieving Items from a Collection.
An index in the Collection class is an integer between one (1) and the number of items in the collection. You can control the initial value of an item's index, using the before and after named parameters, but its value may change as other items are added and deleted. For more information, see the Add method.
You can use the index to iterate over the items in a collection. For example, the following code shows two ways to give all the employees in a collection of Employee objects a 10 percent raise, assuming that the variable employeesCollection
contains a reference to a Collection object:
Option Strict On
Dim counter As Integer
Dim emp As Employee
For counter = 1 To employeesCollection.Count
emp = CType(employeesCollection(counter), Employee)
emp.Rate *= 1.1
Next
' Alternative code follows.
Dim emp As Employee
For Each emp In employeesCollection
emp.Rate *= 1.1
Next
Note If you attempt to use For Each with a collection that contains items of a different type than the one being iterated, an ArgumentException is thrown.