How to Sort a List by a property in the object

2018-12-31 02:52发布

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

List<Order> objListOrder = new List<Order>();
GetOrderList(objListOrder); // fill list of orders

Now I want to sort the list based on one property of the Order object, for example I need to sort it by the order date or order id.

How can i do this in C#?

19条回答
一个人的天荒地老
2楼-- · 2018-12-31 03:52

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

查看更多
登录 后发表回答