2

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 :)

1
  • You can pass in an object that implement IComparer to the sort method. That would let you do any custom logic to determine how to arrange the results. But, you would want to do this sort outside of the For Each bit. Commented Mar 1, 2016 at 20:29

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.