Sorting in Visual Basic .NET

Our example demonstrates sorting for built-in types in Visual Basic .NET. We’ll look at sorting for strings and integers.

Imports System
Imports System.Collections.Generic

Module Program
    Sub Main()
        ' Sorting functions work for any IComparable type in .NET
        Dim strs As New List(Of String) From {"c", "a", "b"}
        strs.Sort()
        Console.WriteLine("Strings: " & String.Join(", ", strs))

        ' An example of sorting integers
        Dim ints As New List(Of Integer) From {7, 2, 4}
        ints.Sort()
        Console.WriteLine("Ints:    " & String.Join(", ", ints))

        ' We can also check if a list is already in sorted order
        Dim s As Boolean = ints.SequenceEqual(ints.OrderBy(Function(x) x))
        Console.WriteLine("Sorted:  " & s.ToString())
    End Sub
End Module

In Visual Basic .NET, we use the List(Of T) class to create dynamic lists that we can sort. The Sort method is available for lists of any type that implements the IComparable interface, which includes built-in types like String and Integer.

For strings, we create a list and use the Sort method to sort it in place. The same approach is used for integers.

To check if a list is already sorted, we compare the original list with a sorted version of itself using SequenceEqual and OrderBy. This is equivalent to the IsSorted function in the original example.

To run the program, save it as Sorting.vb and use the Visual Basic compiler:

$ vbc Sorting.vb
$ mono Sorting.exe
Strings: a, b, c
Ints:    2, 4, 7
Sorted:  True

This example demonstrates basic sorting operations in Visual Basic .NET. The language provides built-in methods for sorting collections, making it straightforward to work with ordered data.