Zochonis
Zochonis

Reputation: 81

how to sort an array of string containing numbers, numerically

So as the title already suggests I simply want to know if it is possible to sort elements that are in a string array via the numbers that are also contained within those strings.

In my program I have been able to read the contents of a file which are laid out like this:

Adele got 2,Jack got 8

I have then been able to split this file via the comma into a string array called names:

Dim fileReader As System.IO.StreamReader
        Dim line As String
        fileReader = My.Computer.FileSystem.OpenTextFileReader(ClassA)
        line = fileReader.ReadLine
        names = line.Split(",")
        For Each element As String In names
          Array.Sort(names)
          Console.WriteLine(element)
        Next

I was also able to sort the file alphabetically giving an output of:

Adele got 2
Jack got 8

However what I want to know is whether it is or isn't possible to sort these strings based on the number so the output would look like:

Jack got 8
Adele got 2

I also considered using regex to extract the numbers, parse them as integer, save them to a variable and then add them to an array and compare the arrays but their has to be a simpler way D:

Any help is much appreciated guys :)

Upvotes: 2

Views: 4785

Answers (2)

JerryM
JerryM

Reputation: 885

Yes, it's possible. Add a comparer function, and then sort using it. This is the comparer:

Private Shared Function WhoGotComparer(ByVal x As String, ByVal y As String) As Integer
    Dim parseX() As String = Split(x, " got ")
    Dim parseY() As String = Split(y, " got ")
    If parseX.Length <> 2 Or parseY.Length <> 2 Then Return 0
    Return CInt(parseY(1)).CompareTo(CInt(parseX(1))) 'Performs an integer comparison.
End Function

Add it to your code. You can make use of it like this:

names.Sort(AddressOf WhoGotComparer)

This should result in the array being sorted in descending order. I think that is what you wanted based on the example. If you want to change the order to ascending you can reverse the roles of they x and y parameters in the comparer function, or you can negate the results of the Compare.

Upvotes: 0

Linq to the rescue. I added to the data to be sure it would handle 2 digit numerals and because 2 elements is a feeble test:

Dim phrases As String() = {"Adele got 2", "Zalgo got 9", "Jack got 8", "Ziggy got 11"}

phrases = phrases.OrderByDescending(Function(q) Int32.Parse(q.Split(" ").Last)).ToArray()

For Each s In phrases
    Console.WriteLine(s)
Next

Result:

Ziggy got 11
Zalgo got 9
Adele got 8
Jack got 2

Upvotes: 1

Related Questions