C# linq sort - quick way of instantiating IComparer

后端 未结 5 1254
遥遥无期
遥遥无期 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 04:01

    I have a ProjectionComparer class in MiscUtil, so you can do:

    IComparer comparer = ProjectionComparer.Create(x => x.Name);
    c.Sort(comparer);
    

    The code is also in this answer.

    You can create a Comparison 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.Create to do the same thing.

提交回复
热议问题