C# linq sort - quick way of instantiating IComparer

后端 未结 5 1239
遥遥无期
遥遥无期 2021-02-01 03:42

When using linq and you have

c.Sort()

Is there any good inline way of defining a Comparison and/or IComparer class w

相关标签:
5条回答
  • 2021-02-01 03:51

    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;
        }
    }
    
    0 讨论(0)
  • 2021-02-01 03:52

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

    0 讨论(0)
  • 2021-02-01 03:54

    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
    
    0 讨论(0)
  • 2021-02-01 04:00

    That's one of the uses of lambda expressions:

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

    0 讨论(0)
  • 2021-02-01 04:01

    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.

    0 讨论(0)
提交回复
热议问题