VB.NET

.NET Array Class File String Sub ArrayList Cast Console DataTable DateTime Dictionary Enum For If IndexOf Interface Lambda LINQ List Nothing Parse Process Property Regex Replace Select Sort Split StringBuilder Substring

Sort

Sort. Elements,
one after another,
proceed in order. But often collections are not in an order we want. With the Sort subroutine (on arrays and lists) we order elements by their values.


Descending: sort order

We sort collections in-place. Sorting is by default in ascending order: elements go from lowest to highest. We can implement a descending order.


Array

Array. We use System.Array.Sort on array instances. The array is of type String() and it contains five strings. When Sort is called, we can specify the type of the array parameter after Of.

Here:The array is sorted in-place. Then, we loop through the array with a For-Each loop. We print results.

Based on:

.NET 4.5

VB.NET program that uses System.Array.Sort on strings

Module Module1
    Sub Main()
	' Create an array of String() with five elements.
	Dim array As String() = New String() {"Egyptian", _
	    "Indian", _
	    "American", _
	    "Chinese", _
	    "Filipino"}
	' Use the System.Array.Sort shared method.
	System.Array.Sort(Of String)(array)
	' Loop through the results.
	Dim value As String
	For Each value In array
	    Console.WriteLine(value)
	Next
    End Sub
End Module

Output

American
Chinese
Egyptian
Filipino
Indian
Reverse

Sort, Reverse. Another way to reorder an array combines the Sort and Reverse methods. Effectively, this will give you a reverse alphabetical sort on strings.

Tip:It is important to use Reverse after Sort, because Sort will always produce an alphabetical array in this context.

VB.NET program that uses Sort and Reverse methods

Module Module1
    Sub Main()
	' Create an array of String() with five elements.
	Dim array As String() = New String() {"X", _
	    "B", _
	    "A", _
	    "Z", _
	    "C"}
	' Use the System.Array.Sort shared method.
	System.Array.Sort(Of String)(array)
	' Invoke the Reverse method after sorting.
	System.Array.Reverse(array)
	' Loop through the results.
	Dim value As String
	For Each value In array
	    Console.WriteLine(value)
	Next
    End Sub
End Module

Output

Z
X
C
B
A
List

List. Sorting a List is also easy. No custom algorithms need to be implemented. Instead, you can invoke the instance Sort method on the List you created.

Info:Internally, this uses similar code to the System.Array.Sort method so performance is similar.

Next:In this program, we sort the adjectives and then print them out to the screen.

VB.NET program that uses List Sort method

Module Module1
    Sub Main()
	' Create a list of strings.
	Dim list As New List(Of String)
	list.Add("Australian")
	list.Add("Mongolian")
	list.Add("Russian")
	list.Add("Austrian")
	list.Add("Brazilian")
	' Use Sort method.
	list.Sort()
	' Loop through the results.
	Dim value As String
	For Each value In list
	    Console.WriteLine(value)
	Next
    End Sub
End Module

Output

Australian
Austrian
Brazilian
Mongolian
Russian
Collections: circles in square

Collections. It is also possible to sort collections such as the Dictionary. With this type, we can get the Keys and Values and then sort those collections. We can also sort a List.

Sort DictionarySort List
Miscellaneous

Custom. It is possible to define a custom method that determines sort ordering. The default sorting methods work for many cases. But sometimes problems have additional complexity.

Alphanumeric:We sort strings alphanumerically. This treats digits in strings not as characters but part of perhaps larger numbers.

Alphanumeric Sorting

Files:We sort files by their lengths, from largest to smallest. This example uses the OrderByDescending method.

Sort Files, Size

Numbers, strings:We can sort strings that have numbers within them by parsing each string into an object. Then we sort the object.

Sort Number Strings
Convert or change

With IComparable, we can sort objects based on some part of their internal data. Often we sort objects by a property value. We implement the IComparable generic interface and CompareTo.

IComparable
List

SortedList. Some collections keep their element sorted as you use them.
The SortedList type,
for example,
always sorts its keys. We add keys and values to SortedList.

Add:In Add, the first argument is the key to add. The second argument is the value at that key.

Tip:The SortedList has no ways to reorder its elements. If you want to change the ordering, you must create a new collection.

VB.NET program that uses SortedList

Module Module1
    Sub Main()
	' Create SortedList and add Strings to it.
	Dim sorted As SortedList(Of String, String) =
	    New SortedList(Of String, String)

	sorted.Add("dog", "red")
	sorted.Add("cat", "black")
	sorted.Add("zebra", "black and white")
	sorted.Add("ant", "black")

	' Loop over pairs in the collection.
	For Each pair As KeyValuePair(Of String, String) In sorted
	    Console.WriteLine(pair.Key + "/" + pair.Value)
	Next
    End Sub
End Module

Output

ant/black
cat/black
dog/red
zebra/black and white
Copy: new object copied

Copy. The Array.Sort method sorts in-place. So you must make a copy of the original array if you wish to keep one in that order. Here I use the Array.Copy method.

Note:The changes you make to one copy of the array are not reflected in the other. The two arrays are in separate, unconnected memory.

VB.NET program that uses Copy, Sort

Module Module1
    Sub Main()
	Dim names() As String = {"Zach", "Andrew", "David"}

	' Create a copy of names array and sort it.
	Dim namesCopy(2) As String
	Array.Copy(names, namesCopy, 3)
	Array.Sort(namesCopy)

	' Display arrays.
	Console.WriteLine(String.Join(",", names))
	Console.WriteLine(String.Join(",", namesCopy))
    End Sub
End Module

Output

Zach,Andrew,David
Andrew,David,Zach
The VB.NET programming language

A summary. Sorting strings can be done in several different ways. Here we sampled three of the ways you can sort strings in alphabetical order, and also reverse alphabetical order.


Summary: 300, 200 and 100

Typically, the sorting methods provided by .NET are sufficient. They are well-tested. They are bug-free for strings and other value types like Integers.