I have a class called Order
which has properties such as OrderId
, OrderDate
, Quantity
, and Total
. I have a l
// Totally generic sorting for use with a gridview
public List Sort_List(string sortDirection, string sortExpression, List data)
{
List data_sorted = new List();
if (sortDirection == "Ascending")
{
data_sorted = (from n in data
orderby GetDynamicSortProperty(n, sortExpression) ascending
select n).ToList();
}
else if (sortDirection == "Descending")
{
data_sorted = (from n in data
orderby GetDynamicSortProperty(n, sortExpression) descending
select n).ToList();
}
return data_sorted;
}
public object GetDynamicSortProperty(object item, string propName)
{
//Use reflection to get order type
return item.GetType().GetProperty(propName).GetValue(item, null);
}