Sort array problem (VB)

phillip

Freshman
Joined
Aug 28, 2003
Messages
37
I have an array containing letters and numbers that im trying to sort.

using the array sort method i'm not geting the results im after

Example

A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
A11
A20

Is being sorted.

A1
A10
A11
A2
A20
A3
A4
A5
A6
A7
A8
A9
 
Last edited:
It looks like the sort method is sorting the entries as strings (alphabetical order where 10 comes before 9). There is a sort method for the Array Class that takes an IComparer as an argument. It looks like you'll have to write a class that impliments the IComparer interface to get the desired sort that you want. There is tons of good info on the internet to help you out.

Here's some MSDN info on the method you want with a mediocre example. That should be enough to get you started.
 
The sort function is sorting them correctly based on the elements being strings. If you desire a different sort order then you might want to look at creating a customised implementation of IComparer.

The following snippet should give you a basic idea.

Visual Basic:
Class Testing
    Implements IComparer

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim x1 As String, y1 As String
        x1 = DirectCast(x, String)
        y1 = DirectCast(y, String)

        Dim i1, i2 As Integer

        i1 = Integer.Parse(x1.Substring(1))
        i2 = Integer.Parse(y1.Substring(1))

        If i1 > i2 Then Return 1
        If i1 < i2 Then Return -1
        Return 0


    End Function
End Class

This can then be called from a method like
Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim a() As String = {"a1", "a10", "a3"}

        Dim x As IComparer

        Array.Sort(a, New Testing)

    End Sub
 
Back
Top