«

»

Apr 02 2008

Sorting a String Array

Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript were forced to write their own sort routines, be that a bubble sort, a heap sort, a quicksort, or some other type of sorting algorithm.

But that was before the advent of the .NET Framework. If you have the .NET Framework installed on your computer then you can sort an array using code no more complicated than this:

Based on http://www.microsoft.com/technet/scriptcenter/funzone/games/tips08/gtip1130.mspx

Set DataList = CreateObject("System.Collections.ArrayList")

DataList.Add "A"
DataList.Add "E"
DataList.Add "D"
DataList.Add "F"
DataList.Add "B"
DataList.Add "C"

DataList.Sort()

For Each strItem in DataList
    Print strItem
Next

In this script we start off by creating an instance of the System.Collections.ArrayList object, with System.Collections.ArrayList being a .NET class used for creating dynamic arrays. After creating our arraylist object we then use the Add method to add all the items to the array:

DataList.Add "A"
DataList.Add "E"
DataList.Add "D"
DataList.Add "F"
DataList.Add "B"
DataList.Add "C"

Once we’ve populated the arraylist we can then sort the data simply by calling the Sort method:

DataList.Sort()

After that all we have to do is set up a For Each loop and echo back the values within the array:

For Each strItem in DataList
    Print strItem
Next

Needless to say, that’s way easier than writing your own bubble sort routine. Just remember to create an arraylist object (not a regular VBScript array), and to add items to that arraylist one at a time. Do that, and you’ll be able to sort string arrays with the best of them.

As for sorting items in descending order, well, to be honest, we couldn’t find a straightforward method for doing that (at least not without creating and using yet another .NET object). Therefore, we came up with a simple little workaround instead:

Comments are closed.