C# - 使用扩展方法排序
lambda 表达式对人员列表进行排序,
List<Person> persons=new List<Person>();
persons.Add(new Person("Jon","Bernald",45000.89));
persons.Add(new Person("Mark","Drake",346.89));
persons.Add(new Person("Bill","Watts",456.899));
我想根据
public enum CompareOptions
{
ByFirstName,
ByLastName,
BySalary
}
public enum SortOrder
{
Ascending,
Descending
}
排序的方法是什么?
public static List<Person> SortPeople(this List<Person> lst,
CompareOptions opt1,SortOrder ord)
{
lst.Sort((p,op1,op2)=>{ how to apply lambda expression here});
}
I want to sort a list of person say
List<Person> persons=new List<Person>();
persons.Add(new Person("Jon","Bernald",45000.89));
persons.Add(new Person("Mark","Drake",346.89));
persons.Add(new Person("Bill","Watts",456.899));
based on
public enum CompareOptions
{
ByFirstName,
ByLastName,
BySalary
}
public enum SortOrder
{
Ascending,
Descending
}
using lambda expression what is the way to go for sorting?
public static List<Person> SortPeople(this List<Person> lst,
CompareOptions opt1,SortOrder ord)
{
lst.Sort((p,op1,op2)=>{ how to apply lambda expression here});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您似乎正在尝试调用
List
上的 Sort 方法,该方法采用Comparison
委托。这需要一些工作,因为您首先必须定义一个兼容的比较函数。第一步是根据
CompareOptions
值编写一个比较函数。默认情况下,该函数将按升序排序。如果您希望它下降,只需否定该值即可。 版本来完成,
所以现在编写 SortPeople 可以通过以下EDIT
该版本 100% 在 lambda 中完成
It looks like you are attempting to call the Sort method on
List<T>
which takes aComparison<T>
delegate. This will require a bit of work because you first have to define a compatible comparison function.First step is to write a comparison function based on the
CompareOptions
valueBy default this function will sort in ascending order. If you want it to be descending simply negate the value. So now writing SortPeople can be done by the following
EDIT
Version which is done 100% in a lambda
你真的需要枚举吗?我不认为将搜索逻辑封装在方法中比仅使用 linq 方法更清晰或更干燥:
等等。
Do you really need the enums? I don't think that encapsulating your search logic in a method is much clearer or more DRY than just using linq methods:
etc.
要使其在 lambda 中工作,表达式需要形成
比较
签名。这将需要 2 个“Person”实例。你可以这样做:To get this to work in a lambda, the expression needs to form a
Comparison<T>
signature. This would take 2 "Person" instances. You could do this like:}
}