C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The array is sorted in-place. Then we loop through the array with a For-Each loop. We print results.
For Each, ForConsoleVB.NET program that uses Array.Sort on strings
Module Module1
Sub Main()
' Create an array of String() with 4 elements.
Dim vegatables As String() = New String() {"carrot",
"turnip",
"onion",
"corn"}
' Use the System.Array.Sort shared method.
System.Array.Sort(vegatables)
' Loop through the results and print them with Console.WriteLine.
Dim value As String
For Each value In vegatables
Console.WriteLine(value)
Next
End Sub
End Module
Output
carrot
corn
onion
turnip
Tip: It is important to use Reverse after Sort, because Sort will always produce an alphabetical array in this context.
Array.ReverseVB.NET program that uses Sort and Reverse methods
Module Module1
Sub Main()
' Create a String array with 5 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
Info: In DescendingComparison, we create a descending sort by changing the order of the variables in the CompareTo call.
Tip: We use AddressOf to reference our special Comparison Function. Then we use For-Each to display the result.
VB.NET program that uses descending sort
Module Module1
Function DescendingComparison(ByVal valueA As String,
ByVal valueB As String) As Integer
' Invert the order of the comparison to sort in descending order.
Return valueB.CompareTo(valueA)
End Function
Sub Main()
Dim letters As String() = {"X",
"B",
"A",
"Z",
"C"}
' Use custom DescendingComparison to sort in reverse.
Array.Sort(Of String)(letters, New Comparison(Of String)(AddressOf DescendingComparison))
' Display results.
For Each value As String In letters
Console.WriteLine("DESCENDING: {0}", value)
Next
End Sub
End Module
Output
DESCENDING: Z
DESCENDING: X
DESCENDING: C
DESCENDING: B
DESCENDING: A
Info: Internally, this uses similar code to the System.Array.Sort method so performance is similar.
Next: In this program, we sort the room objects (furniture) 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 and add 4 Strings to it.
Dim list As New List(Of String)
list.Add("chair")
list.Add("table")
list.Add("desk")
list.Add("couch")
' Use Sort method.
list.Sort()
' Loop through the results and display them.
Dim value As String
For Each value In list
Console.WriteLine(value)
Next
End Sub
End Module
Output
chair
couch
desk
table
Here: We create a List of 3 integers, and then Sort it in descending (high to low) order, using a lambda expression.
VB.NET program that uses lambda, sorts List
Module Module1
Sub Main()
Dim numbers = New List(Of Integer)({20, 30, 40})
' Use lambda to sort list in descending order.
numbers.Sort(Function(valueA, valueB) valueB.CompareTo(valueA))
For Each number As Integer In numbers
Console.WriteLine("LAMBDA SORTED NUMBER: {0}", number)
Next
End Sub
End Module
Output
LAMBDA SORTED NUMBER: 40
LAMBDA SORTED NUMBER: 30
LAMBDA SORTED NUMBER: 20
Note: The changes you make to one copy of the array are not reflected in the other. The 2 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
ComparisonTwoTuples: Receives 2 tuples and returns an Integer. We call CompareTo—if the first comparison is 0, we use a second comparison.
Result: The list is sorted ascending on the first Integer in each tuple, and then descending on the second Integer.
VB.NET program that sorts on 2 Tuple values
Module Module1
Function GetData() As List(Of Tuple(Of Integer, Integer))
Dim result As New List(Of Tuple(Of Integer, Integer))
result.Add(New Tuple(Of Integer, Integer)(100, 1))
result.Add(New Tuple(Of Integer, Integer)(100, 2))
result.Add(New Tuple(Of Integer, Integer)(10, 2))
result.Add(New Tuple(Of Integer, Integer)(10, 1))
Return result
End Function
Function ComparisonTwoTuples(ByVal tupleA As Tuple(Of Integer, Integer),
ByVal tupleB As Tuple(Of Integer, Integer)) As Integer
' Compare the first Item of each tuple in ascending order.
Dim part1 As Integer = tupleA.Item1
Dim part2 As Integer = tupleB.Item1
Dim compareResult As Integer = part1.CompareTo(part2)
' If not equal, return the comparison result.
If compareResult <> 0 Then
Return compareResult
End If
' Compare the second item of each tuple in descending order.
Return tupleB.Item2.CompareTo(tupleA.Item2)
End Function
Sub Main()
Dim data As List(Of Tuple(Of Integer, Integer)) = GetData()
data.Sort(New Comparison(Of Tuple(Of Integer, Integer))(AddressOf ComparisonTwoTuples))
For Each value In data
Console.WriteLine("SORTED ON 2 VALUES: {0}", value)
Next
End Sub
End Module
Output
SORTED ON 2 VALUES: (10, 2)
SORTED ON 2 VALUES: (10, 1)
SORTED ON 2 VALUES: (100, 2)
SORTED ON 2 VALUES: (100, 1)
Version 1: We create a List, add 3 elements to it, and then call Sort. The List is sorted in-place.
Version 2: This code creates a SortedSet, and when we call Add(), each item is stored in a sorted order—we never need to call Sort.
Result: It is faster to use the SortedSet. Avoiding Sort altogether seems to be a consistent performance boost.
VB.NET program that benchmarks List, SortedSet
Module Module1
Sub Main()
Dim m As Integer = 100000
Dim s1 As Stopwatch = Stopwatch.StartNew
' Version 1: add 3 strings to List, then Sort it.
For i As Integer = 0 To m - 1
Dim list = New List(Of String)
list.Add("zebra")
list.Add("20")
list.Add("bird")
list.Sort()
If list.Count <> 3 Then
Return
End If
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
' Version 2: add 3 strings to SortedSet.
For i As Integer = 0 To m - 1
Dim sorted = New SortedSet(Of String)
sorted.Add("zebra")
sorted.Add("20")
sorted.Add("bird")
If sorted.Count <> 3 Then
Return
End If
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
End Sub
End Module
Output
405.52 ns List, Sort
357.17 ns SortedSet
Alphanumeric: We sort strings alphanumerically. This treats digits in strings not as characters but part of perhaps larger numbers.
Alphanumeric SortFiles: We sort files by their lengths, from largest to smallest. This example uses the OrderByDescending method.
Sort Files, SizeNumbers, 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