Sorting By Functions in Visual Basic .NET

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Visual Basic .NET.

Imports System
Imports System.Linq

Module Program
    Sub Main()
        Dim fruits As String() = {"peach", "banana", "kiwi"}

        ' We implement a comparison function for string lengths.
        Dim lenCmp As Comparison(Of String) = Function(a, b) a.Length.CompareTo(b.Length)

        ' Now we can call Array.Sort with this custom comparison function to sort fruits by name length.
        Array.Sort(fruits, lenCmp)
        Console.WriteLine(String.Join(", ", fruits))

        ' We can use the same technique to sort a list of values that aren't built-in types.
        Class Person
            Public Property Name As String
            Public Property Age As Integer

            Public Sub New(name As String, age As Integer)
                Me.Name = name
                Me.Age = age
            End Sub

            Public Overrides Function ToString() As String
                Return $"{{Name = {Name}, Age = {Age}}}"
            End Function
        End Class

        Dim people As New List(Of Person) From {
            New Person("Jax", 37),
            New Person("TJ", 25),
            New Person("Alex", 72)
        }

        ' Sort people by age using LINQ's OrderBy method.
        ' Note: If the Person class is large, you may want to use a List(Of Person) instead
        ' and adjust the sorting function accordingly. If in doubt, benchmark!
        people = people.OrderBy(Function(p) p.Age).ToList()
        Console.WriteLine(String.Join(", ", people))
    End Sub
End Module

To run the program, save it as SortingByFunctions.vb and use the VB.NET compiler:

$ vbc SortingByFunctions.vb
$ mono SortingByFunctions.exe
kiwi, peach, banana
{Name = TJ, Age = 25}, {Name = Jax, Age = 37}, {Name = Alex, Age = 72}

In this Visual Basic .NET example, we’ve used Array.Sort with a custom Comparison(Of String) delegate to sort the fruits array by string length. For sorting custom objects, we’ve used LINQ’s OrderBy method, which provides a more idiomatic approach in .NET for sorting collections.

The Person class is defined as a nested class within the module for simplicity, but in a real-world scenario, you might want to define it in a separate file.

Note that Visual Basic .NET uses different syntax for anonymous functions (lambda expressions) and type declarations compared to other languages. The Function(a, b) syntax is used for lambda expressions, and type declarations come after variable names.