Rein
Rein

Reputation: 911

Array.Sort() by string tkey

I have two arrays; indexArray() as String, and valueArray() as Decimal.

indexArray is actually a list of numbers, in string format. I'd like to sort the indexArray (while keeping corresponding values in valueArray the same) by ascending numerical order of its decimal counterparts.

Here is what I've tried:

Array.Sort(Of String, Decimal)(indexArray, valueArray, Nothing)

I've looked into IComparer objects, but I couldn't get a good grasp on how to make one do what I need, but I'm certain that's likely the answer; or maybe something even simpler that I don't know enough to think of!

Upvotes: 0

Views: 85

Answers (1)

Steve
Steve

Reputation: 216293

Not sure if there is another way, so let's wait if someone has a better idea, but you could use a list of a custom class to store your values and then ask Linq OrderBy method to sort your list of values

Sub Main
    Dim indexArray() as String = {"1.1", "12.2", "10.3", "2.4", "2.1"}
    Dim valueArray() as Decimal = {1.1, 12.2, 10.3, 2.4, 2.1}

    Dim listOfValues = new List(Of MyValues)
    for x = 0 to indexArray.Length - 1
        listOfValues.Add(new MyValues() With {.stringValue = indexArray(x), .decimalValue = valueArray(x)})
    Next

    Dim result = listOfValues.OrderBy(Function(x) x.decimalValue)

    for each mv in result
        Console.WriteLine(mv.stringValue)
    Next

End Sub

Class MyValues
    Public stringValue as String
    Public decimalValue as Decimal
End Class

Upvotes: 3

Related Questions