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're re-assigning the sorted data straight back to your pf.Holdings
property, so why not bypass the overhead of OrderBy
and ToList
and just use the list's Sort method directly instead?
You could use a map to hold Comparison<T> delegates for all the supported sortings and then call Sort(Comparison<T>) with the appropriate delegate:
if (frm.SelectedSortColumn.IsBaseColumn)
{
Comparison<Holding> comparison;
if (!_map.TryGetValue(frm.SelectedSortColumn.BaseColumn, out comparison))
throw new InvalidOperationException("Can't sort on BaseColumn");
if (frm.SortAscending)
pf.Holdings.Sort(comparison);
else
pf.Holdings.Sort((x, y) => comparison(y, x));
}
// ...
private static readonly Dictionary<PortfolioSheetMapping, Comparison<Holding>>
_map = new Dictionary<PortfolioSheetMapping, Comparison<Holding>>
{
{ PortfolioSheetMapping.IssueId, GetComp(x => x.Product.IssueId) },
{ PortfolioSheetMapping.MarketId, GetComp(x => x.Product.MarketId) },
{ PortfolioSheetMapping.Symbol, GetComp(x => x.Symbol) },
// ...
};
private static Comparison<Holding> GetComp<T>(Func<Holding, T> selector)
{
return (x, y) => Comparer<T>.Default.Compare(selector(x), selector(y));
}