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?
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 use of lambda expressions:
c.Sort( (x,y) => x.A.CompareTo(y.A))
EDIT: Fixed example to return int (using CompareTo) instead of bool
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...
I've no idea what c.Sort()
is in your example, as it can be many things (do you mean List<T>.Sort()
?), but one thing that it sure isn't is LINQ. LINQ doesn't have 'Sort() - it has
OrderBy()`.
That said, the latter also works with IComparer
, and there's no way to create an instance of anonymous class implementing the interface "inline", so you'll have to define a class.
For List<T>.Sort()
, there is an overload which takes Comparison<T>
. Since it's a delegate type, you can use a lambda to provide the function inline:
List<int> xs = ...;
xs.Sort((x, y) => y - x); // reverse sort
If the objects in the List c already implement IComparable you wont need another one. But if you need custom comparison, you can implement IComparer in a nested class. You also can use a lambda expression to create a Comparison method on the fly:
persons.Sort( (person1, person2) => person1.Age.CompareTo( person2.Age ) );