在VB.NET中对多维数组进行排序

nss*_*yom 3 .net vb.net arrays string multidimensional-array

我有一个像这样的2X50阵列-

R-125212,11
C-254645,25
R-456598,96
M-456878,35
O-980857,89
And so on...
Run Code Online (Sandbox Code Playgroud)

现在,我想使用第二列的值对该数组进行排序。因此输出应如下所示:

R-125212,11
C-254645,25
M-456878,35
O-980857,89
R-456598,96
And so on...
Run Code Online (Sandbox Code Playgroud)

如何使用VB.NET轻松做到这一点?如果还有其他更好的方法不使用数组就可以得到相似的结果,那也对我有帮助。

3vt*_*vts 6

我建议使用 aList(Of Tuple)而不是数组。它更加动态。请检查此代码:

Sub SortList()
    'Declare the List Of Tuple with a Tuple of Char, Integer, Integer
    Dim lstToSort As New List(Of Tuple(Of Char, Integer, Integer))
    'Example to Add items
    lstToSort.Add(Tuple.Create("R"c, 250645, 11))
    lstToSort.Add(Tuple.Create("C"c, 125212, 25))
    'Sort is just 1 line
    lstToSort = lstToSort.OrderBy(Function(i) i.Item2).ToList
    'Loop through the elements to print them
    For Each tpl As Tuple(Of Char, Integer, Integer) In lstToSort
        Console.WriteLine(tpl.Item1 & "-" & tpl.Item2 & "," & tpl.Item3)
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)

编辑:鉴于您对问题的编辑,此处的代码已修复:

Sub SortList()
    'Declare the List Of Tuple with a tuple of String, Integer
    Dim lstToSort As New List(Of Tuple(Of String, Integer))
    'Example to add items
    lstToSort.Add(Tuple.Create("R-250645", 11))
    lstToSort.Add(Tuple.Create("C-125212", 25))
    'Sort is just 1 line
    lstToSort = lstToSort.OrderBy(Function(i) i.Item2).ToList
    'Loop through the elements to print them
    For Each tpl As Tuple(Of String, Integer) In lstToSort
        Console.WriteLine(tpl.Item1 & "," & tpl.Item2)
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)

尝试一下,让我知道您的意见

  • 这对于我遇到的类似问题非常有效! (2认同)

SSS*_*SSS 5

您的问题有很多可能的解决方案,但以我的经验,最好是使用System.Data.DataTable

Dim dtb As New System.Data.DataTable
dtb.Columns.Add("Column1")
dtb.Columns.Add("Column2", GetType(Integer))
dtb.Rows.Add("Z-123456", 2)
dtb.Rows.Add("R-125212", 11)
dtb.Rows.Add("C-254645", 25)
dtb.Rows.Add("R-456598", 96)
dtb.Rows.Add("M-456878", 35)
dtb.Rows.Add("O-980857", 89)
Dim dvw As DataView = dtb.DefaultView
dvw.Sort = "Column2 ASC"
Dim dtbSorted As DataTable = dvw.ToTable()
DataGridView1.DataSource = dtbSorted
Run Code Online (Sandbox Code Playgroud)