简体   繁体   中英

C# linq sort - quick way of instantiating IComparer

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?

这是 lambda 表达式的用途之一:

c.Sort( (x,y) => xACompareTo(yA))

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;
    }
}

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 ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM