Dman
Dman

Reputation: 573

Sort Multidimensional array by Number

I am trying to sort a 2 dimensional array. The first column is a number and the second one is a word.

So far I am using:

myarray.Sort(Function(x, y) x(1).CompareTo(y(1)))

but it only sorts in alphabetical order, and I need it to sort in numerical order

Upvotes: 0

Views: 2891

Answers (2)

Dman
Dman

Reputation: 573

After searching around, I found an answer to my problem.

Convert the second column to an integer and then sort.

Then you can put in back into a .tolist

myarray = myarray.OrderByDescending(Function(r) Convert.ToInt32(r(1))).ToList()

Upvotes: 0

Once you store a numbers as a string it cannot act as a number any longer because it is a numeral (a character representing a number). This is especially true of sorting where "9" will evaluate greater than "10000" everytime. Rather than a string array, use a utility class to store the Name and Value as a NamedValuePair:

Public Class NVP
    Public Property Name As String
    Public Property Value As Integer

    Public Sub New(n As String, v As Integer)
        Name = n
        Value = v
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("{0} ({1})", Name, Value.ToString)
    End Function
End Class

Then store those in your list:

Private myList As New List(Of NVP)

For a simple sort on the value member:

' populate some fake data
myList.Add(New NVP("Ziggy", 6))
myList.Add(New NVP("Apple", 1))
myList.Add(New NVP("Zebra", 152))
myList.Add(New NVP("Zoey", 7))

' Sort or OrderBy are not methods, so create a new list in the desired order:
myList = myList.OrderBy(Function(x) x.Value).ToList()

The NVP class can be very handy for a lots of situations. To make it even more useful, define it as Generic so it can be declared as string/decimal or string/Date, string Point etc etc etc:

Public Class NVP(Of T)
    Public Property Name As String
    Public Property Value As T

    Public Sub New(n As String, v As T)
        Name = n
        Value = v
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("{0} ({1})", Name, Value.ToString)
    End Function
End Class

Usage:

Dim foo As New NVP(Of Integer)(strName, intVal)   ' int type

Dim myList As New List(Of NVP(Of Double))         ' double type

Upvotes: 2

Related Questions