Using lambda expression in place of IComparer argument

haughtonomous picture haughtonomous · May 30, 2013 · Viewed 34.9k times · Source

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

Answer

Jeppe Stig Nielsen picture Jeppe Stig Nielsen · May 30, 2013

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)
    );