I am making a program which has two arrays, both are strings. I want to sort the second string alphabetically and the first string needs to go with the second string. I then need to display them both, with the secodn string in alphabetical order with the appropiate name(first string) next to it.

8 Years
Discussion Span
Last Post by Monza

What have you done so far? Do you understand how arrays work? Have you chosen a sorting algorithm?

Edited by Nick Evan: n/a


VB array.sort only works with single dimension array, so quickest way would be to use the IComparer function to allow VB.net array sort function to work with your custom array structure.

create an array structure (or you could use a class) to hold both your strings in a single object variable

Public Class MainForm
    Public Structure twoStrings
        Public string1 As String
        Public string2 As String
    End Structure

    Sub main()
        'place all your strings into the new duel array
        Dim stringdata(100) As twoStrings

        stringdata(0).string1 = "unsorted string"
        stringdata(0).string2 = "string to sort" '.......etc
        ' stringdata(1).string1 ............

        'and then to sort the data, use
        Array.Sort(stringdata, New SorttwoStrings) 'use sorttwostrings class
    End Sub

    Public Class SorttwoStrings
        'helper routine to sort by structured string value
        Implements IComparer(Of twoStrings)

        Public Function Compare(ByVal s1 As twoStrings, ByVal s2 As twoStrings) As Integer_ Implements System.Collections.Generic.IComparer(Of twoStrings).Compare
            'sort by string2
            If s1.string2 > s2.string2 Then
                Return -1
            ElseIf s2.string2 < s1.string2 Then
                Return 1
                Return 0 ' same value
            End If
        End Function
    End Class
End Class

Edited by Nick Evan: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.