C# lambda expressions and IComparer

前端 未结 4 916
闹比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: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 from a projection.

    So your example would be:

    int index = Array.BinarySearch(widgets, x,
                                   ProjectionComparer.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(
        this TSource[] array,
        TSource value,
        Func keySelector)
    {
        return Array.BinarySearch(array, value,
                                  ProjectionComparer.Create(array, keySelector));
    }
    

提交回复
热议问题