C# lambda expressions and IComparer

前端 未结 4 909
闹比i
闹比i 2021-02-04 03:15

I am using lambda expressions to sort and search an array in C#. I don\'t want to implement the IComparer interface in my class, because I need to sort and search on multiple m

4条回答
  •  梦谈多话
    2021-02-04 03:41

    Try this:

    public static class ComparisonEx
    {
        public static IComparer AsComparer(this Comparison @this)
        {
            if (@this == null)
                throw new System.ArgumentNullException("Comparison @this");
            return new ComparisonComparer(@this);
        }
    
        public static IComparer AsComparer(this Func @this)
        {
            if (@this == null)
                throw new System.ArgumentNullException("Func @this");
            return new ComparisonComparer((x, y) => @this(x, y));
        }
    
        private class ComparisonComparer : IComparer
        {
            public ComparisonComparer(Comparison comparison)
            {
                if (comparison == null)
                    throw new System.ArgumentNullException("comparison");
                this.Comparison = comparison;
            }
    
            public int Compare(T x, T y)
            {
                return this.Comparison(x, y);
            }
    
            public Comparison Comparison { get; private set; }
        }
    }
    

    It lets you use this code:

    Comparison c = (x, y) => x == y ? 0 : (x <= y ? -1 : 1);
    IComparer icc = c.AsComparer();
    
    Func f = (x, y) => x == y ? 0 : (x <= y ? -1 : 1); 
    IComparer icf = f.AsComparer();
    

提交回复
热议问题