C# lambda 表达式和 IComparer

发布于 2024-10-15 13:23:16 字数 1284 浏览 9 评论 0原文

我正在使用 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 conversion lambda expression to type 'System.Collections.IComparer'因为它不是委托类型。由于某种原因,Sort 对 IComparer 和 Comparison 都有重载,但 BinarySearch 仅支持 IComparer。经过一些研究,我发现了笨重的 ComparisonComparer 将比较转换为 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)));

恶心。有更干净的方法吗?

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 member fields.

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

While the sort works fine, the binary search gives a compilation error Cannot convert lambda expression to type 'System.Collections.IComparer<Widget>' because it is not a delegate type. For some reason, Sort has overloads for both IComparer and Comparison, but BinarySearch only supports IComparer. After some research, I discovered the clunky ComparisonComparer<T> to convert the Comparison to an 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);
    }
}

This allows the binary search to work as follows:

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

Yuck. Is there a cleaner way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

叶落知秋 2024-10-22 13:23:16

好吧,一种选择是创建类似 ProjectionComparer 的东西。我在 MiscUtil 中有一个版本 - 它基本上创建了一个 IComparer< 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));
}

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));
}
夜司空 2024-10-22 13:23:16

您可以使用我的 ValueComparer class

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

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

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.

给我一枪 2024-10-22 13:23:16

试试这个:

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();

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();
安稳善良 2024-10-22 13:23:16

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

int index = Array.BinarySearch(
  widgets.Select(x=>x.foo).ToArray(),
  x.foo)

if you want to avoid using external libraries, another option for you would be to first filter out the array and object.
e.g.

int index = Array.BinarySearch(
  widgets.Select(x=>x.foo).ToArray(),
  x.foo)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文