Looking for a better way to sort my List

后端 未结 7 1365
醉梦人生
醉梦人生 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:05

    how about:

    Func sortBy;
    
    switch (frm.SelectedSortColumn.BaseColumn)
    {
        case PortfolioSheetMapping.IssueId:
            sortBy = c => c.Product.IssueId;
            break;
        case PortfolioSheetMapping.MarketId:
            sortBy = c => c.Product.MarketId;
            break;
        /// etc.
    }
    
    /// EDIT: can't use var here or it'll try to use IQueryable<> which doesn't Reverse() properly
    IEnumerable sorted = pf.Holdings.OrderBy(sortBy);
    if (!frm.SortAscending)
    {
        sorted = sorted.Reverse();
    }
    

    ?

    Not exactly the fastest solution, but it's reasonably elegant, which is what you were asking for!

    EDIT: Oh, and with the case statement, it probably needs refactoring to a seperate function that returns a Func, not really a nice way to get rid of it entirely, but you can at least hide it away from the middle of your procedure !

提交回复
热议问题