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:
Add | Adds an element with the specified key and value to a SortedList object |
Clear | Removes all elements from a SortedList object |
Clone | Creates a shallow copy of a SortedList object |
Contains | Determines whether a SortedList object contains a specific key |
ContainsKey | Determines whether a SortedList object contains a specific key |
ContainsValue | Determines whether a SortedList object contains a specific value |
GetByIndex | Gets the value at the specified index of a SortedList object |
GetKey | Gets the key at the specified index of a SortedList object |
IndexOfKey | Returns the zero-based index of the specified key in a SortedList object |
IndexOfValue | Returns the zero-based index of the first occurrence of the specified value in a SortedList object |
Remove | Removes the element with the specified key from a SortedList object |
RemoveAt | Removes the element at the specified index of a SortedList object |
SetByIndex | Replaces the value at a specific index in a SortedList object |
TrimToSize | Sets the capacity to the actual number of elements in a SortedList object |
Capacity | Gets or sets the capacity of a SortedList object |
Count | Gets the number of elements contained in a SortedList object |
page last modified: 2016-09-19; loaded in 0.0014 seconds