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.
You could try reducing the switch to something like this:
private static readonly Dictionary> sortingOperations = new Dictionary>
{
{PortfolioSheetMapping.Symbol, h => h.Symbol},
{PortfolioSheetMapping.Quantitiy, h => h.Quantitiy},
// more....
};
public static List SortHoldings(this List holdings, SortOrder sortOrder, PortfolioSheetMapping sortField)
{
if (sortOrder == SortOrder.Decreasing)
{
return holdings.OrderByDescending(sortingOperations[sortField]).ToList();
}
else
{
return holdings.OrderBy(sortingOperations[sortField]).ToList();
}
}
You could populate sortingOperations with reflection, or maintain it by hand. You could also make SortHoldings accept and return an IEnumerable and remove the ToList calls if you don't mind calling ToList in the caller later. I'm not 100% sure that OrderBy is happy receiving an object, but worth a shot.
Edit: See LukeH's solution to keep things strongly typed.