C#lambda表达式和的IComparer [英] C# lambda expressions and IComparer

查看:842
本文介绍了C#lambda表达式和的IComparer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



虽然排序工作正常,二进制搜索给出了一个编译错误的无法转换lambda表达式到类型System.Collections.IComparer<窗口小部件>',因为它不是一个委托类型的。出于某种原因,排序中同时包含的IComparer和比较过载,而二分查找只支持IComparer的。经过一番研究,我发现了笨重的 ComparisonComparer< T> 来比较到的IComparer转换:

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?

推荐答案

好了,一个选项是创建类似 ProjectionComparer 来代替。我有在 MiscUtil 一个版本 - 它基本上是创建一个的IComparer< T> 从投影

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.

所以,你的例子是:

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

这篇关于C#lambda表达式和的IComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆