Using .NET Interops in VBScript - Sorting Arrays in VBScript
(Page 2 of 4 )
Admittedly, VBScript does not have very good support for working with arrays. It lacks many necessary features that are common to other languages. One example of this is the ability to sort the elements in an array. While Jscript provides adequate support for this, VBScript does not. Thankfully, .NET also provides support for this in a scriptable COM interop.
Set DataList = CreateObject("System.Collections.ArrayList")
DataList.Add "B"
DataList.Add "C"
DataList.Add "E"
DataList.Add "D"
DataList.Add "A"
The System.Collections.ArrayList class creates a specialized collection object. As with traditional collections, you can add data using the Add method. It also exposes several methods that are not available to traditional collection objects.
DataList.Sort()
For Each strItem in DataList
WScript.Echo strItem
Next
The Sort method will sort the data elements in ascending order.
DataList.Reverse()
For Each strItem in DataList
WScript.Echo strItem
Next
The Reverse method can be used to reverse the order of the elements. Using this method in conjunction with the Sort method results in a descending order.
DataList.Remove("D")
WScript.Echo "Count:", DataList.Count
DataList.RemoveAt(3)
WScript.Echo "Count:", DataList.Count
Elements can also be removed from the collection by value or index with the Remove and RemoveAt methods respectively. You can also see how the Count property returns the number of elements in the collection.
DataList.Insert 3, "C"
WScript.Echo "Count:", DataList.Count
You can insert data at a specific index by using the Insert method. Elements after the specified index will be increased by one. The capacity of the collection will be automatically increased to house the new data without losing any existing elements.
arrData = DataList.ToArray
For i = 0 To UBound(arrData)
WScript.Echo arrData(i)
Next
You can return a standard array of the elements in the collection by using the ToArray method.
DataList.Clear()
WScript.Echo "Count:", DataList.Count
Finally, there is also a clear method for dumping all remaining elements at once.
Next: Working with Strings >>
More Windows Scripting Articles
More By Nilpo