Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Comparer from a lambda function easily?

Tags:

c#

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.

like image 941
edeboursetty Avatar asked Dec 15 '22 21:12

edeboursetty


2 Answers

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.

like image 161
Jeppe Stig Nielsen Avatar answered Jan 06 '23 15:01

Jeppe Stig Nielsen


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);  
    }  
}  
like image 32
Mare Infinitus Avatar answered Jan 06 '23 15:01

Mare Infinitus