Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Multidimensional Array in VB.NET

I have a 2X50 array like this-

R-125212,11
C-254645,25
R-456598,96
M-456878,35
O-980857,89
And so on...

Now I want to sort this array with the values of the 2nd Column. So the output should look like-

R-125212,11
C-254645,25
M-456878,35
O-980857,89
R-456598,96
And so on...

How to do this with VB.NET easily? If there is other better way to have the similar result without using array, that also will help me.

like image 942
nsssayom Avatar asked Apr 03 '17 07:04

nsssayom


2 Answers

There are many possible solutions to your question, but in my experience the best is to use a 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
like image 158
SSS Avatar answered Nov 09 '22 22:11

SSS


I would recommend the use of a List(Of Tuple) instead of an array. It is more dynamic. Please check this code:

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

Edit: Given your edit on the question here is the code fixed:

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

Give it a try and let me know your comments

like image 20
3vts Avatar answered Nov 09 '22 22:11

3vts