C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We create an array of strings. Then we create a new Comparison<string> object using the CompareLength method as the target.
Finally: We sort the array again using this Comparison delegate and display it.
CompareLength: We use CompareTo with the lengths of both strings. CompareTo returns an integer value indicating the comparison result.
CompareToReverse: To reverse the sort, just reverse the order of the CompareTo expression variables.
C# program that uses Comparison delegate
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);
}
}
}
Output
bird
elephant
dog
cat
mouse
cat
dog
bird
mouse
elephant
C# program that uses Comparison lambda
using System;
class Program
{
static void Main()
{
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));
}
}
Output
RESULT: 1;22;333;4444
Tip: You can often implicitly use the Comparison delegate by just passing the target method name.
Also: A Comparison can be used with the List.Sort or Array.Sort methods. Try caching the lambda for a small speedup.
Sort ListArray.Sort