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?
That's one of the uses of lambda expressions:
c.Sort( (x,y) => x.A.CompareTo(y.A))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With