CompareTo FunctionCall the CompareTo function on an Integer to determine whether a value would be sorted before, after, or the same.
This page was last reviewed on Dec 30, 2023.
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.
Sort List
Example. 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.
Part 1 We compare the low value "a" to the high value "b" and the result is -1, meaning "a" is smaller.
Part 2 When we compare a high value to a low value, the result is 1, meaning the first value is larger than the second.
Part 3 When 2 equal values are compared, the result is 0. When sorting, this would mean no more reordering is needed.
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 Module
LOW CompareTo HIGH: -1 HIGH CompareTo LOW: 1 EQUAL CompareTo: 0
Summary. 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.
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 (new).
© 2007-2024 Sam Allen.