SortedList: Add

Add

Adds an element with the specified key and value to a SortedList object..



 Public Sub Add(
	  ByRef Key As Variant,
	  ByRef Value As Variant )

Parameters

Key
[ByRef] Variant. The value to used to maintain a sorted order.
Value
[ByRef] Variant. The value associated with the key.

Remark

The insertion point is determined based on the comparer selected, either explicitly or by default, when the SortedList object was created.

You can also use the Item property to add new elements by setting the value of a key that does not exist in the SortedList object (for example, myCollection("myNonexistentKey") = myValue). However, if the specified key already exists in the SortedList, setting the Item property overwrites the old value. In contrast, the Add method does not modify existing elements.

The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created.

Exceptions

Exception Condition
ArgumentException An element with the specified Key already exists in the SortedList object.
-or-
The comparer throws an exception.
NotSupportedException The SortedList is read-only.
-or-
The SortedList has a fixed size.

Examples

The following code example shows how to add elements to a SortedList object.

Public Sub Main()
    Dim List As New SortedList
    
    List.Add "one", "The"
    List.Add "two", "quick"
    List.Add "three", "brown"
    List.Add "four", "fox"
    
    Debug.Print "The SortedList contains the following sorted by key:"
    PrintKeysAndValues List
End Sub

Private Sub PrintKeysAndValues(ByVal List As SortedList)
    Dim i As Long
    
    Debug.Print "-KEY-", "-VALUE-"
    
    For i = 0 To List.Count - 1
        Debug.Print List.GetKey(i), List.GetByIndex(i)
    Next
    
    Debug.Print
End Sub

' This code produces the following output.
'
'    The SortedList contains the following:
'    -KEY-         -VALUE-
'    four          fox
'    one           The
'    three         brown
'    two           quick

See Also

Project CorLib Overview

Class SortedList Overview

Item

IComparer