19

我正在使用 lambda 表达式在 C# 中对数组进行排序和搜索。我不想在我的类中实现 IComparer 接口,因为我需要对多个成员字段进行排序和搜索。

class Widget
{
    public int foo;

    public void Bar()
    {
        Widget[] widgets;

        Array.Sort(widgets, (a, b) => a.foo.CompareTo(b.foo));

        Widget x = new Widget();
        x.foo = 5;
        int index = Array.BinarySearch(widgets, x,
                                       (a, b) => a.foo.CompareTo(b.foo));
    }
}

虽然排序工作正常,但二进制搜索给出了编译错误Cannot convert lambda expression to type 'System.Collections.IComparer<Widget>' because it is not a delegate type。出于某种原因,Sort 对 IComparer 和比较都有重载,但 BinarySearch 仅支持 IComparer。经过一番研究,我发现ComparisonComparer<T>将比较转换为 IComparer 很笨重:

public class ComparisonComparer<T> : IComparer<T>
{
    private readonly Comparison<T> comparison;

    public ComparisonComparer(Comparison<T> comparison)
    {
        this.comparison = comparison;
    }

    int IComparer<T>.Compare(T x, T y)
    {
        return comparison(x, y);
    }
}

这允许二进制搜索按如下方式工作:

int index = Array.BinarySearch(
  widgets,
  x,
  new ComparisonComparer<Widget>((a, b) => a.foo.CompareTo(b.foo)));

呸。有没有更清洁的方法?

4

4 回答 4

9

好吧,一种选择是创建类似的东西ProjectionComparer。我在MiscUtilIComparer<T>中有一个版本 - 它基本上从投影创建一个。

所以你的例子是:

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

或者你可以实现你自己的扩展方法T[]来做同样的事情:

public static int BinarySearchBy<TSource, TKey>(
    this TSource[] array,
    TSource value,
    Func<TSource, TKey> keySelector)
{
    return Array.BinarySearch(array, value,
                              ProjectionComparer.Create(array, keySelector));
}
于 2011-02-02T02:37:07.867 回答
9

您可以使用我的ValueComparer<T>课程

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

您可以通过传递多个 lambda 表达式来按多个属性进行比较。

于 2011-02-02T02:42:30.937 回答
3

尝试这个:

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; }
    }
}

它允许您使用以下代码:

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();
于 2011-02-02T03:07:36.530 回答
0

如果您想避免使用外部库,另一种选择是首先过滤掉数组和对象。例如

int index = Array.BinarySearch(
  widgets.Select(x=>x.foo).ToArray(),
  x.foo)
于 2020-12-20T18:55:11.933 回答