到位的IComparer参数的使用lambda表达式 [英] Using lambda expression in place of IComparer argument
本文介绍了到位的IComparer参数的使用lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能与C#传递lambda表达式作为一个方法调用的IComparer的说法?
Is it possible with C# to pass a lambda expression as an IComparer argument in a method call?
如像
var x = someIEnumerable.OrderBy(aClass e => e.someProperty,
(aClass x, aClass y) => { return x.someProperty > y.SomeProperty ? 1 : x.someProperty < y.SomeProperty ? -1 : 0; }
);
我不能完全得到这个编译所以我猜没有,但似乎这样的lambda表达式和匿名委托,我觉得我必须做一些愚蠢的错误之间明显的协同效应。
I can't quite get this to compile so I'm guessing not, but it seems such an obvious synergy between lambdas and anonymous delegates that I feel I must be doing something foolishly wrong.
TIA
推荐答案
由于叶普指出,如果你在.NET 4.5中,可以使用静态方法的Comparer< T> .Create
As Jeppe points out, if you're on .NET 4.5, you can use the static method Comparer<T>.Create
.
,这是应该是等价的实现:
If not, this is an implementation that should be equivalent:
public class FunctionalComparer<T> : IComparer<T>
{
private Func<T, T, int> comparer;
public FunctionalComparer(Func<T, T, int> comparer)
{
this.comparer = comparer;
}
public static IComparer<T> Create(Func<T, T, int> comparer)
{
return new FunctionalComparer<T>(comparer);
}
public int Compare(T x, T y)
{
return comparer(x, y);
}
}
这篇关于到位的IComparer参数的使用lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文