C# linq sort - quick way of instantiating IComparer

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.


Jon's answer is great but can be a little bit out of date, with release of .NET 4.5 we now (finally!) have this awesome method Comparer<T>.Create

items.Sort((x, y) => x.Value.CompareTo(y.Value)); //sorting List<T>                
items.OrderBy(x => x, Comparer<Item>.Create((x, y) => x.Value.CompareTo(y.Value))); //sorting IEnumerable<T>

Assuming Item is defined something like:

class Item
{
    public readonly int Key;
    public readonly string Value;

    public Item(int key, string value)
    {
        Key = key;
        Value = value;
    }
}

Tags:

C#

Linq