C#lambda表达式和的IComparer

编程入门 行业动态 更新时间:2024-10-19 07:28:20
本文介绍了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) { thisparison = 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

本文发布于:2023-11-08 07:33:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568739.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   lambda   IComparer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!