如何轻松地从lambda函数创建比较器? [英] How to create a Comparer from a lambda function easily?
问题描述
我想知道.Net框架中是否提供了一个实现IComparer的类,并且可以从lambda函数构造它.这样做会很有用:
I am wondering if there was a class provided in the .Net framework that implements IComparer and that can be constructed from a lambda function. That would be useful to be able to do:
void SortByLength(List<string> t)
{
t = t.OrderBy(
s => s,
Comparer<string>.FromLambda((s1,s2) => s1.Length.CompareTo(s2.Length))
).ToList();
}
比每次都定义一个Comparer类要容易得多.我知道创建这样的FromLambda方法并不复杂,但是我想知道框架中是否存在现有的方法,因为我认为这是一个非常常见的功能.
It would be much easier than having to define a Comparer class each time. I know it is not complicated to create such a FromLambda method, but I was wondering if there was an existing way in the framework as I see this as being a pretty common feature.
推荐答案
为什么要这么难?
按长度排序列表很简单:
Ordering the list by length is as simple as:
var ordered = list.OrderBy(s => s.Length);
如果您真的需要那些复杂的东西,则可以使用CompareComparer可以帮助您.请在此处查看:将比较结果转换为icomparer
If you really need that complicated stuff, the ComparisonComparer could help you out. Please have a look here: Converting Comparison to icomparer
这是从lamda或委托中构建IComparer!
This is building an IComparer from a lamda or delegate!
这是该示例中的基本代码
Here is the essential code from that example
public class ComparisonComparer<T> : IComparer<T>
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public int Compare(T x, T y)
{
return _comparison(x, y);
}
}
这篇关于如何轻松地从lambda函数创建比较器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!