CompareTo
Is one value smaller, bigger or the same size as another value? By calling CompareTo
, we can get this information, which is useful for sorting elements.
Instead of writing complicated If chains repeatedly, we can just invoke CompareTo
on 2 Integers, Strings and other values. We often use CompareTo
within a lambda used for sorting.
We have 3 Integers in the Main
subroutine. Two of them are equal to 5, and one is much larger and is equal to 100. We call CompareTo
on these Integers.
Module Module1 Sub Main() Dim a as Integer = 5 Dim b as Integer = 100 Dim c as Integer = 5 ' Part 1: compare a low value to a high value. Dim ab = a.CompareTo(b) Console.WriteLine($"LOW CompareTo HIGH: {ab}") ' Part 2: compare a high value to a low value. Dim ba = b.CompareTo(a) Console.WriteLine($"HIGH CompareTo LOW: {ba}") ' Part 3: compare two equal values. Dim ca = c.CompareTo(a) Console.WriteLine($"EQUAL CompareTo: {ca}") End Sub End ModuleLOW CompareTo HIGH: -1 HIGH CompareTo LOW: 1 EQUAL CompareTo: 0
CompareTo
is almost always used within sorting functions, like lambda expressions passed to List.Sort
. Its result can be returned directly, as it will result in a correct sorting order.