Home
VB.NET
Sort List Example
This page was last reviewed on Dec 30, 2023.
Dot Net Perls
Sort List. A VB.NET List can be sorted. The List type has a useful subroutine called Sort that will sort your List either by a default sorting order or with a custom one.
Type notes. Instead of using String instances in your List, you can use other types such as Integer or even Class types. All of these things can be sorted, but a lambda argument may be needed.
List
Sort
Sort with lambda. Here, we create a List of strings, and then call Sort with a lambda expression argument. Our lambda expression begins with the Function keyword and receives 2 String parameters.
Next It returns the result of CompareTo on the Length properties of the String parameters.
CompareTo
String Length
Tip This means the List is sorted in ascending order by the lengths of its strings, from shortest to longest.
Lambda
Module Module1 Sub Main() Dim l As List(Of String) = New List(Of String) l.Add("mississippi") l.Add("indus") l.Add("danube") l.Add("nile") ' Sort using lambda expression. l.Sort(Function(elementA As String, elementB As String) Return elementA.Length.CompareTo(elementB.Length) End Function) For Each element As String In l Console.WriteLine(element) Next End Sub End Module
nile indus danube mississippi
Simple example. This example creates a List of three String instances. Then it invokes the Sort subroutine. This subroutine does not return a value—instead it changes the List to be sorted.
Finally We loop through the sorted List—the strings are now in alphabetical order.
Module Module1 Sub Main() Dim l As List(Of String) = New List(Of String) l.Add("tuna") l.Add("velvetfish") l.Add("angler") ' Sort alphabetically. l.Sort() For Each element As String In l Console.WriteLine(element) Next End Sub End Module
angler tuna velvetfish
Reverse List. The Reverse subroutine inverts the order of the elements in the List from their original order. It does no sorting. As with Sort, you do not need to assign anything to the result.
Array.Reverse
Module Module1 Sub Main() Dim l As List(Of String) = New List(Of String) l.Add("anchovy") l.Add("barracuda") l.Add("bass") l.Add("viperfish") ' Reverse list. l.Reverse() For Each element As String In l Console.WriteLine(element) Next End Sub End Module
viperfish bass barracuda anchovy
A summary. We can sort the elements in a List using the parameterless Sort subroutine and also with a lambda expression. It is possible to Reverse the order of the elements in your List.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 30, 2023 (edit link).
Home
Changes
© 2007-2024 Sam Allen.