How to Sort a List by a property in the object

前端 未结 20 2012
醉梦人生
醉梦人生 2020-11-21 08:25

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a l

20条回答
  •  一向
    一向 (楼主)
    2020-11-21 08:54

    None of the above answers were generic enough for me so I made this one:

    var someUserInputStringValue = "propertyNameOfObject i.e. 'Quantity' or 'Date'";
    var SortedData = DataToBeSorted
                       .OrderBy(m => m.GetType()
                                      .GetProperties()
                                      .First(n => 
                                          n.Name == someUserInputStringValue)
                       .GetValue(m, null))
                     .ToList();
    

    Careful on massive data sets though. It's easy code but could get you in trouble if the collection is huge and the object type of the collection has a large number of fields. Run time is NxM where:

    N = # of Elements in collection

    M = # of Properties within Object

提交回复
热议问题