我正在尝试对二维数组进行排序。第一列是数字,第二列是单词。
到目前为止,我正在使用:
myarray.Sort(Function(x, y) x(1).CompareTo(y(1)))
但它只按字母顺序排序,我需要按数字顺序排序
答案 0 :(得分:2)
将数字存储为字符串后,它不能再作为数字,因为它是一个数字(字符代表一个数字)。对于“9”每次评估大于“10000”的排序尤其如此。使用实用程序类将Name和Value存储为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
然后将其存储在您的列表中:
Private myList As New List(Of NVP)
对值成员进行简单排序:
' 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()
对于很多情况,NVP课程非常方便。要使它甚至 more 有用,请将其定义为Generic,以便将其声明为字符串/小数或字符串/日期,字符串Point等等:
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
用法:
Dim foo As New NVP(Of Integer)(strName, intVal) ' int type
Dim myList As New List(Of NVP(Of Double)) ' double type
答案 1 :(得分:0)
搜索完之后,我找到了问题的答案。
将第二列转换为整数然后排序。
然后你可以回到.tolist
myarray = myarray.OrderByDescending(Function(r) Convert.ToInt32(r(1))).ToList()