I want to sort a list of person say
List persons=new List();
persons.Add(new Person(\"Jon\",\"Bernald\",45000.89));
persons.Add(new P
It looks like you are attempting to call the Sort method on List
which takes a Comparison
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
value
private static Comparison 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();
}
}
By 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
public static List SortPeople(
this List list,
CompareOptions opt1,
SortOrder ord) )
var original = Create(opt1);
var comp = original;
if( ord == SortOrder.Descending ) {
comp = (x,y) => -(orig(x,y));
}
list.Sort(comp);
}
EDIT
Version which is done 100% in a lambda
public static List SortPeople(
this List list,
CompareOptions opt1,
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;
});
}