我想排列一个人的名单
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 }
使用lambda表达方式进行排序是什么?
public static List<Person> SortPeople(this List<Person> lst,CompareOptions opt1,SortOrder ord) { lst.Sort((p,op1,op2)=>{ how to apply lambda expression here}); }
解决方法
看起来您正在尝试调用List< T>中的Sort方法.其采用比较< T>代表.这将需要一些工作,因为您首先必须定义兼容的比较功能.
第一步是根据CompareOptions值写一个比较函数
private static Comparison<Person> Create(CompareOptions opt) { switch (opt) { case CompareOptions.ByFirstName: (x,y) => x.FirstName.CompareTo(y.FirstName); case CompareOptions.ByLastName: (x,y) => x.LastName.CompareTo(y.LastName); case CompareOptions.BySalary: (x,y) => x.Salary - y.Salary; default: throw new Exception(); } }
默认情况下,此功能将按升序排序.如果你希望它下降,就简单地否定这个值.所以现在编写SortPeople可以通过以下方式完成
public static List<Person> SortPeople( this List<Person> list,SortOrder ord) ) var original = Create(opt1); var comp = original; if( ord == SortOrder.Descending ) { comp = (x,y) => -(orig(x,y)); } list.Sort(comp); }
编辑
在lambda中完成100%的版本
public static List<Person> SortPeople( this List<Person> list,SortOrder ord) ) list.Sort( (x,y) => { int comp = 0; switch (opt) { case CompareOptions.ByFirstName: comp = x.FirstName.CompareTo(y.FirstName); case CompareOptions.ByLastName: comp = x.LastName.CompareTo(y.LastName); case CompareOptions.BySalary: comp = x.Salary.CompareTo(y.Salary); default: throw new Exception(); } if ( ord == SortOrder.Descending ) { comp = -comp; } return comp; }); }