XTab's Blog

Ged Mead's Blog at vbCity

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

JanFebruary 2010Mar
SMTWTFS
31123456
78910111213
14151617181920
21222324252627
28123456
78910111213

Archives

Topics

Ramblings

VB.NET

Sorting a single array is a simple task. You just run the Shared Sort method on the array:

        Dim arCustomers() As String = {"Williams", "Brown", "Smith", "Jones", "Green"}

        Array.Sort(arCustomers)

        For Each Str As String In arCustomers

            Console.WriteLine(Str)

        Next

The resulting output is:

Brown
Green
Jones
Smith
Williams

Things get more complicated if you have two arrays that have a logical link - maybe one array contains a list of names and a second array contains a numeric value for each of those names:

    Dim arNames() As String = {"Smith", "Jones", "White", "Mead", "Knobbe", "Baranovsky", "Bonner"}

    Dim arIDNumber() As Integer = {234, 123, 765, 999, 357, 543, 666}

If you want to sort the Names array so that the name with the lowest IDNumber is first and the name with the highest IDNumber is last, then you can use an overloaded version of the Sort method:

        '  Sort the array of Names based on their IDNumbers

        Array.Sort(arIDNumber, arNames)

Note that you must assign the Key (the IDNumbers array) before the Item (the Names array) to get the correct result, which is:

Jones
Smith
Knobbe
Baranovsky
Bonner
White
Mead

Jones has an IDNumber of 123 and Mead has an IDNumber of 999.

Of course, the sort doesn't have to have a numeric key. It is just as easy to sort the IDNumber values based on the alphabetical order of the Names, if this is needed.

        Array.Sort(arNames, arIDNumber)

One potential Gotcha that isn't immediately obvious is that this Sort action will also sort the IDNumber array at the same time. It makes complete sense for this to happen when you think about it, but if for some reason you only wanted the re-sorted arrays to be temporary, you will have take a slightly different approach.

One of the easiest ways is to create a clone of the original arrays and you can sort the cloned copies while leaving the original in their default order.

        Dim arNames2() As String = arNames.Clone()

        Dim arScores2() As Integer = arIDNumber.Clone()

        Array.Sort(arScores2, arNames2)

You will then have your original arrays left unchanged and the index sorted versions available for use.

posted on Monday, July 06, 2009 9:14 AM

Feedback

No comments posted yet.

Post Feedback

Title:
Name:
Url:
Comments: 
Protected by Clearscreen.SharpHIPEnter the code you see: