Lambda example. 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.
Result We sort the 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
Requirements. 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.
Tip You can often implicitly use the Comparison delegate by just passing the target method name.
Notes, target method. 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.
Discussion. 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.
Summary. 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.
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 Apr 10, 2024 (edit).