Looking for a better way to sort my List

后端 未结 7 1327
醉梦人生
醉梦人生 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 18:56

    Have you looked into Dynamic LINQ

    Specifically, you could simply do something like:

    var column = PortFolioSheetMapping.MarketId.ToString();
    if (frm.SelectedSortColumn.IsBaseColumn)
    {
        if (frm.SortAscending)
             pf.Holdings = pf.Holdings.OrderBy(column).ToList();
        else
             pf.Holdings = pf.Holdings.OrderByDescending(column).ToList();
    }
    

    Note: This does have the constraint that your enum match your column names, if that suits you.

    EDIT

    Missed the Product property the first time. In these cases, DynamicLINQ is going to need to see, for example, "Product.ProductId". You could reflect the property name or simply use a 'well-known' value and concat with the enum .ToString(). At this point, I'm just really forcing my answer to your question so that it at least is a working solution.

提交回复
热议问题