Looking for a better way to sort my List

后端 未结 7 1397
醉梦人生
醉梦人生 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 delegates for all the supported sortings and then call Sort(Comparison) with the appropriate delegate:

    if (frm.SelectedSortColumn.IsBaseColumn)
    {
        Comparison 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>
        _map = new Dictionary>
        {
            { PortfolioSheetMapping.IssueId,  GetComp(x => x.Product.IssueId) },
            { PortfolioSheetMapping.MarketId, GetComp(x => x.Product.MarketId) },
            { PortfolioSheetMapping.Symbol,   GetComp(x => x.Symbol) },
            // ...
        };
    
    private static Comparison GetComp(Func selector)
    {
        return (x, y) => Comparer.Default.Compare(selector(x), selector(y));
    }
    

提交回复
热议问题