Collection.Add Method |
Microsoft.VisualBasic.Collection
objectvariable.Add item [, key, before, after ]
The name of the Collection object to which an item is to be added
An object of any type that specifies the member to add to the collection
A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection
The member to be added placed in the collection before the member identified by the before argument (more on this in Section )
The member to be added placed in the collection after the member identified by the after argument (more on this in Section )
Adds an object to a collection
If you do not specify a before or after value, the member is appended to the end of the collection (in index order).
If you do not specify a key value, you cannot access this member using a key , but instead must access it either by using its ordinal number or by enumerating all the members of the collection with the For Each...Next construct. Thus, keys are highly recommended.
The before or after argument can refer to an index or a key. For instance, consider the following code:
Dim c As New Collection( ) c.Add("donna", "111") c.Add("steve", "222") 'c.Add("bill", "333", "222") 'c.Add("bill", "333", 2) MsgBox(c.Item(2))
Both of the commented lines of code adds the item "bill" between "donna" and "steve." The first line uses the key to specify the before object, and the second line specifies the ordinal position of the before object.
Key values must be unique or an error (runtime error 457, "This key is already associated with an element of this collection") is generated.
You can specify a before or after position, but not both.
colComposers.Add(Item:="Ludwig von Beethoven" _ Key:="Beethoven")
Using named parameters helps to self-document your code:
colMyCollection.Add Item:="VB.NET Language in a Nutshell" _ Key:="Title"
If your key parameter is a value being brought in from outside your program, you must ensure that each value is always unique. One method for doing this is illustrated in the entry for the Collection.Item Method.
Collection Class, Collection.Count Property, Collection.Item Method, Collection.Remove Method