Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lambda expression in place of IComparer argument

Is it possible with C# to pass a lambda expression as an IComparer argument in a method call?

eg something like

var x = someIEnumerable.OrderBy(aClass e => e.someProperty,  (aClass x, aClass y) =>    x.someProperty > y.SomeProperty ?  1 : x.someProperty < y.SomeProperty ?  -1 : 0); 

I can't quite get this to compile so I'm guessing not, but it seems such an obvious synergy between lambdas and anonymous delegates that I feel I must be doing something foolishly wrong.

TIA

like image 363
haughtonomous Avatar asked May 30 '13 14:05

haughtonomous


People also ask

Can we write a Parameterless lambda expression?

No, there isn't. Lambda expressions are optimised (in terms of syntax) for the single parameter case. I know that the C# team feels your pain, and have tried to find an alternative. Whether there ever will be one or not is a different matter.

What is the difference between statement lambda and expression lambda?

The difference between a statement and an expression lambda is that the statement lambda has a statement block on the right side of the lambda operator, whereas the expression lambda has only an expression (no return statement or curly braces, for example).

Can we use dynamic in lambda expression?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.

Can lambda expression have more than one statement?

Yes, you can use multiple lines.


2 Answers

If you're on .NET 4.5, you can use the static method Comparer<aClass>.Create.

Documentation: Comparer<T>.Create Method .

Example:

var x = someIEnumerable.OrderBy(e => e.someProperty,      Comparer<aClass>.Create((x, y) => x.someProperty > y.SomeProperty ?  1 : x.someProperty < y.SomeProperty ?  -1 : 0)     ); 
like image 180
Jeppe Stig Nielsen Avatar answered Oct 12 '22 06:10

Jeppe Stig Nielsen


As Jeppe points out, if you're on .NET 4.5, you can use the static method Comparer<T>.Create.

If not, this is an implementation that should be equivalent:

public class FunctionalComparer<T> : IComparer<T> {     private Func<T, T, int> comparer;     public FunctionalComparer(Func<T, T, int> comparer)     {         this.comparer = comparer;     }     public static IComparer<T> Create(Func<T, T, int> comparer)     {         return new FunctionalComparer<T>(comparer);     }     public int Compare(T x, T y)     {         return comparer(x, y);     } } 
like image 27
Timothy Shields Avatar answered Oct 12 '22 06:10

Timothy Shields