Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous IComparer implementation

Tags:

c#

Is it possible to define an anonymous implementation of IComparer?

I believe Java allows anonymous classes to be defined inline - does C#?

Looking at this code I want to define a custom IComparer inline

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(     this IEnumerable<TSource> source,     Func<TSource, TKey> keySelector,     IComparer<TKey> comparer ) 
like image 603
Jack Kada Avatar asked Mar 13 '11 11:03

Jack Kada


1 Answers

As indicated in one of the comments below, .Net 4.5 allows this via a static method on the Comparer<> class, e.g. comparing two objects based on the value of a property in the class:

var comparer = Comparer<KilowattSnapshot>.Create(          (k1, k2) => k1.Kilowatt.CompareTo(k2.Kilowatt) ); 

Obviously this can be used inline rather than assigned to a variable.

like image 71
David Clarke Avatar answered Oct 05 '22 06:10

David Clarke