Looking for a better way to sort my List

后端 未结 7 1324
醉梦人生
醉梦人生 2021-01-02 18:37

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.

相关标签:
7条回答
  • 2021-01-02 19:20

    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));
    }
    
    0 讨论(0)
提交回复
热议问题