我正在使用 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)));
呸。有没有更清洁的方法?