I want to create a generalized method for sorting any kind of list by any kind of variable.
E.g. I have a Student and a Class entity:
Order(studentList, s => s.Name, desc)
Order(classList, s => s.ClassName, desc)
I have tried to create a private method for doing this:
private List<T> Order<T, TKey>(List<T> listToOrder, Expression<Func<T, TKey>> sortKey, bool desc)
{
return desc ? listToOrder.OrderByDescending(sortKey) : listToOrder.OrderBy(sortKey)
}
But this obviously doesn't work. Any ideas how I can achieve this? Will edit the answer if it's not sufficient enough.
CodePudding user response:
If your Student
& Class
values are collected, you can try to write an extension method
- return type might be
IOrderedEnumerable<T>
which type fromOrderBy
&OrderByDescending
. - you might not need to use
Expression
just use delegateFunc<T, TKey>
will be enough
as below
public static class MyExtesion{
public static IOrderedEnumerable<T> Order<T, TKey>(this IEnumerable<T> source,Func<T, TKey> sortKey, bool desc)
{
return desc ? source.OrderByDescending(sortKey) : source.OrderBy(sortKey);
}
}
CodePudding user response:
If my understand is correct, try this :
public static List<T> Order<T>(List<T> listToOrder, Func<T, int> sortFunc, bool desc)
{
return desc ?
listToOrder.OrderByDescending(x => sortFunc(x)).ToList() : listToOrder.OrderBy(x => sortFunc(x)).ToList();
}
Following is test codes:
var arr1 = new int[] {1,-1,2,-2,0,3,-3};
var result = LogHelper.Order(arr1.ToList(),x=>x*x,false);
Just log them.