How to sort a list of data classes by multiple columns in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Linq

Module Program

    ' Data class
    Class Item
        Public Property A As Integer
        Public Property B As Integer
        Public Property LabelStr As String

        Public Sub New(a As Integer, b As Integer, labelStr As String)
            Me.A = a
            Me.B = b
            Me.LabelStr = labelStr
        End Sub

        Public Overrides Function ToString() As String
            Return $"({A}, {B}, {LabelStr})"
        End Function
    End Class

    ' Create dataset
    Function MakeData() As List(Of Item)
        Return New List(Of Item) From {
            New Item(7, 2, "python"),
            New Item(8, 3, "c"),
            New Item(3, 5, "c++"),
            New Item(4, 1, "c#"),
            New Item(3, 2, "java"),
            New Item(7, 1, "go"),
            New Item(1, 2, "rust")
        }
    End Function

    ' Sort by column A, then B
    Sub SortData(data As List(Of Item))
        data.Sort(Function(x, y)
                      Dim cmp = x.A.CompareTo(y.A)
                      If cmp <> 0 Then Return cmp
                      Return x.B.CompareTo(y.B)
                  End Function)
    End Sub

    ' Print all items
    Sub PrintData(data As IEnumerable(Of Item))
        For Each item In data
            Console.WriteLine(item)
        Next
    End Sub

    ' Find first item by label
    Function FindByLabel(data As IEnumerable(Of Item), label As String) As Item
        Return data.FirstOrDefault(Function(i) i.LabelStr = label)
    End Function

    ' Filter by first column
    Function FilterByA(data As IEnumerable(Of Item), value As Integer) As List(Of Item)
        Return data.Where(Function(i) i.A = value).ToList()
    End Function

    Sub Main()
        Dim data = MakeData()

        SortData(data)
        Console.WriteLine("Sorted data:")
        PrintData(data)

        Console.WriteLine()
        Console.WriteLine("Searching for 'java':")
        Dim found = FindByLabel(data, "java")
        If found IsNot Nothing Then
            Console.WriteLine(found)
        End If

        Console.WriteLine()
        Console.WriteLine("Filtering items where A = 7:")
        Dim filtered = FilterByA(data, 7)
        PrintData(filtered)
    End Sub

End Module

					


' run:
'
' Sorted data:
' (1, 2, rust)
' (3, 2, java)
' (3, 5, c++)
' (4, 1, c#)
' (7, 1, go)
' (7, 2, python)
' (8, 3, c)
' 
' Searching for 'java':
' (3, 2, java)
' 
' Filtering items where A = 7:
' (7, 1, go)
' (7, 2, python)  
'

 



answered Jan 29 by avibootz

Related questions

...