I\'m reviewing a piece of code I wrote not too long ago, and I just hate the way I handled the sorting - I\'m wondering if anyone might be able to show me a better way.
Have you looked into Dynamic LINQ
Specifically, you could simply do something like:
var column = PortFolioSheetMapping.MarketId.ToString();
if (frm.SelectedSortColumn.IsBaseColumn)
{
if (frm.SortAscending)
pf.Holdings = pf.Holdings.OrderBy(column).ToList();
else
pf.Holdings = pf.Holdings.OrderByDescending(column).ToList();
}
Note: This does have the constraint that your enum match your column names, if that suits you.
EDIT
Missed the Product
property the first time. In these cases, DynamicLINQ is going to need to see, for example, "Product.ProductId"
. You could reflect the property name or simply use a 'well-known' value and concat with the enum .ToString()
. At this point, I'm just really forcing my answer to your question so that it at least is a working solution.