VB.NET Sort

Array Collections File Keyword String Cast Class Console Data Directive Enum Exception If Interface Lambda LINQ Loop Nothing Number Process Property Regex Select Sort StringBuilder Structure Sub Time Windows

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. We sort collections in-place.

Array

We use System.Array.Sort on array instances. The array instance is of type String() and it contains five strings. When the System.Array.Sort method is called, you can specify the type of the array parameter in the first parentheses.

Array

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

Program that uses System.Array.Sort on strings: VB.NET

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

Sort, Reverse

Reverse

Another way to reorder an array combines the Sort and Reverse methods. Effectively, this will give you a reverse alphabetical sort on strings. First invoke the System.Array.Sort method. We then use the System.Array.Reverse method.

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

Program that uses Sort and Reverse methods: VB.NET

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 in the VB.NET programming language is also easy to do. 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.

Program that uses List Sort method: VB.NET

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

Collections: circles in square

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. More information also is available on sorting a List collection.

Sort DictionarySort List

Custom

Miscellaneous

It is possible, and often useful, to define a custom method that determines how a collection is sorted. 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 SortingAbout part

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

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 its CompareTo method.

IComparable

SortedList

List

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. In Add, the first argument is the key to add, and the second is its value.

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

Program that uses SortedList: VB.NET

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

Copy: new object copied

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. We see the array initialization syntax. The two arrays are kept separate.

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.

Program that uses Copy, Sort: VB.NET

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

Summary

The VB.NET programming language

Sorting strings in the VB.NET language 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.

Typically:The sorting methods provided by .NET are ideal.
They are well-tested.
They are bug-free for strings.

VB.NET