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});
}
}
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: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
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.