Comparison
This .NET type enables custom sorting. In C# it is often used with Array.Sort
or List.Sort
. We implement Comparison
using its constructor.
The target is a method that receives 2 parameters of the appropriate type and returns an int
. It determines sorting order of the parameters.
We do not need to use a static
method for the Comparison
implementation. We can instead use a lambda expression. Here we sort on string
lengths with a lambda Comparison
.
using System; string[] array = { "4444", "1", "22", "333" }; // Use lambda to sort on length. Array.Sort(array, (a, b) => a.Length.CompareTo(b.Length)); // Write result. Console.WriteLine("RESULT: {0}", string.Join(";", array));RESULT: 1;22;333;4444
In this program we create an array of strings. We create a new Comparison
object using the CompareLength
method as the target.
CompareTo
with the lengths of both strings. CompareTo
returns an integer value indicating the comparison result.string
array by each string
's length in ascending order with the delegate CompareLength
.using System; class Program { static int CompareLength(string a, string b) { // Return result of CompareTo with lengths of both strings. return a.Length.CompareTo(b.Length); } static void Main() { // Source array. string[] array = { "bird", "elephant", "dog", "cat", "mouse" }; // Display array. foreach (string element in array) { Console.WriteLine(element); } Console.WriteLine(); // Create Comparison instance and use it. Comparison<string> comparison = new Comparison<string>(CompareLength); Array.Sort(array, comparison); // Display array. foreach (string element in array) { Console.WriteLine(element); } } }bird elephant dog cat mouse cat dog bird mouse elephant
The Comparison
type requires that you specify a method that receives two parameters of type T and then returns an int
. You pass the method name to the constructor.
Comparison
delegate by just passing the target method name.How do you implement the code inside the target method (like CompareLength
)? Use the CompareTo
method on a property, field, or other value from each type.
There are many other examples of using Comparison
. You can use Comparison
without specifying the constructor explicitly. It is compatible with the lambda expression syntax.
Comparison
can be used with the List.Sort
or Array.Sort
methods. Try caching the lambda for a small speedup.We looked at the Comparison
type. We provided an example of the Comparison
constructor. And we pointed out that it is not necessary to provide in all cases.