C# lambda expressions and IComparer

∥☆過路亽.° 提交于 2019-12-02 22:43:54

Well, one option is to create something like ProjectionComparer instead. I've got a version of that in MiscUtil - it basically creates an IComparer<T> from a projection.

So your example would be:

int index = Array.BinarySearch(widgets, x,
                               ProjectionComparer<Widget>.Create(x => x.foo));

Or you could implement your own extension methods on T[] to do the same sort of thing:

public static int BinarySearchBy<TSource, TKey>(
    this TSource[] array,
    TSource value,
    Func<TSource, TKey> keySelector)
{
    return Array.BinarySearch(array, value,
                              ProjectionComparer.Create(array, keySelector));
}

You can use my ValueComparer<T> class:

int index = Array.BinarySearch(
    widgets, x,
    new ValueComparer<Widget>(x => x.Foo)
);

You can compare by multiple properties by passing multiple lambda expressions.

Try this:

public static class ComparisonEx
{
    public static IComparer<T> AsComparer<T>(this Comparison<T> @this)
    {
        if (@this == null)
            throw new System.ArgumentNullException("Comparison<T> @this");
        return new ComparisonComparer<T>(@this);
    }

    public static IComparer<T> AsComparer<T>(this Func<T, T, int> @this)
    {
        if (@this == null)
            throw new System.ArgumentNullException("Func<T, T, int> @this");
        return new ComparisonComparer<T>((x, y) => @this(x, y));
    }

    private class ComparisonComparer<T> : IComparer<T>
    {
        public ComparisonComparer(Comparison<T> 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<T> Comparison { get; private set; }
    }
}

It lets you use this code:

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

Func<int, int, int> f = (x, y) => x == y ? 0 : (x <= y ? -1 : 1); 
IComparer<int> icf = f.AsComparer();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!