How to create a Comparer from a lambda function easily?
c#
Solution
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);
}
}
Problem
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.