Looking for a better way to sort my List

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

    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.

提交回复
热议问题