I am wondering if there was a class provided in the .Net framework that implements IComparer and that can be constructed from a lambda function. That would be useful to be able to do:
void SortByLength(List<string> t)
{
t = t.OrderBy(
s => s,
Comparer<string>.FromLambda((s1,s2) => s1.Length.CompareTo(s2.Length))
).ToList();
}
It would be much easier than having to define a Comparer class each time. I know it is not complicated to create such a FromLambda method, but I was wondering if there was an existing way in the framework as I see this as being a pretty common feature.
The other answers are from before the release of .NET 4.5. But with the BCL of .NET 4.5 (Visual Studio 2012), you simply say
Comparer<string>.Create((s1,s2) => s1.Length.CompareTo(s2.Length))
See the Comparer<T>.Create
documentation.
Why would you make it that difficult?
Ordering the list by length is as simple as:
var ordered = list.OrderBy(s => s.Length);
If you really need that complicated stuff, the ComparisonComparer could help you out. Please have a look here: Converting Comparison to icomparer
This is building an IComparer from a lamda or delegate!
Here is the essential code from that example
public class ComparisonComparer<T> : IComparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public int Compare(T x, T y)
{
return _comparison(x, y);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With