Using lambda expression in place of IComparer argument

前端 未结 3 794
余生分开走
余生分开走 2020-12-08 08:57

Is it possible with C# to pass a lambda expression as an IComparer argument in a method call?

eg something like

var x = someIEnumerable.OrderBy(aClas         


        
3条回答
  •  不思量自难忘°
    2020-12-08 09:45

    As Jeppe points out, if you're on .NET 4.5, you can use the static method Comparer.Create.

    If not, this is an implementation that should be equivalent:

    public class FunctionalComparer : IComparer
    {
        private Func comparer;
        public FunctionalComparer(Func comparer)
        {
            this.comparer = comparer;
        }
        public static IComparer Create(Func comparer)
        {
            return new FunctionalComparer(comparer);
        }
        public int Compare(T x, T y)
        {
            return comparer(x, y);
        }
    }
    

提交回复
热议问题