C# linq sort - quick way of instantiating IComparer

后端 未结 5 1245
遥遥无期
遥遥无期 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:54

    I've no idea what c.Sort() is in your example, as it can be many things (do you mean List.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.Sort(), there is an overload which takes Comparison. Since it's a delegate type, you can use a lambda to provide the function inline:

    List xs = ...;
    xs.Sort((x, y) => y - x); // reverse sort
    

提交回复
热议问题