VBScript Scripting Techniques > Data > SortedList
The .NET SortedList class provides a hash table with automatically sorted key/value pairs.
The available methods and properties are very similar to the ones available in ArrayList.
The following code creates a SortedList and populates it with some key/value pairs:
Set objSortedList = CreateObject( "System.Collections.Sortedlist" )
objSortedList.Add "First", "Hello"
objSortedList.Add "Second", ","
objSortedList.Add "Third", "world"
objSortedList.Add "Fourth", "!"
For i = 0 To objSortedList.Count - 1
WScript.Echo objSortedList.GetKey(i) & vbTab & objSortedList.GetByIndex(i)
Next
This is the resulting output:
First Hello
Fourth !
Second ,
Third world
Note how the list is automatically sorted by keys; it is not possible to sort the list by values.
Like ArrayLists, SortedLists have Count and Capacity properties, and a TrimToSize method, demonstrated in the following code:
WScript.Echo "Size : " & objSortedList.Count
WScript.Echo "Capacity : " & objSortedList.Capacity
WScript.Echo
objSortedList.TrimToSize
WScript.Echo "Size : " & objSortedList.Count
WScript.Echo "Capacity : " & objSortedList.Capacity
This will result in the following output:
Size : 4
Capacity : 16
Size : 4
Capacity : 4
Cloning a SortedList is a piece of cake:
Set objList2 = objSortedList.Clone
WScript.Echo "Sorted List Key(1) = " & objSortedList.GetKey(1)
WScript.Echo "Cloned List Key(1) = " & objList2.GetKey(1)
The result:
Sorted List Key(1) = Fourth
Cloned List Key(1) = Fourth
Available methods and properties are: