Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# linq sort - quick way of instantiating IComparer

Tags:

c#

linq

When using linq and you have

c.Sort()

Is there any good inline way of defining a Comparison and/or IComparer class without actually having to create a separate class?

like image 757
Daniel Avatar asked Sep 04 '09 21:09

Daniel


2 Answers

That's one of the uses of lambda expressions:

c.Sort( (x,y) => x.A.CompareTo(y.A))

like image 153
ckarras Avatar answered Sep 20 '22 03:09

ckarras


I have a ProjectionComparer class in MiscUtil, so you can do:

IComparer<Foo> comparer = ProjectionComparer<Foo>.Create(x => x.Name);
c.Sort(comparer);

The code is also in this answer.

You can create a Comparison<T> instance directly with a lambda expression too, but I don't generally like the duplication that involves. Having said which, it often ends up being somewhat shorter...

EDIT: As noted, as of .NET 4.5, use Comparer<T>.Create to do the same thing.

like image 43
Jon Skeet Avatar answered Sep 22 '22 03:09

Jon Skeet