How to Sort a List by a property in the object

前端 未结 20 1976
醉梦人生
醉梦人生 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

    0 讨论(0)
  • 2020-11-21 08:55

    Based on GenericTypeTea's Comparer :
    we can obtain more flexibility by adding sorting flags :

    public class MyOrderingClass : IComparer<Order> {  
        public int Compare(Order x, Order y) {  
            int compareDate = x.Date.CompareTo(y.Date);  
            if (compareDate == 0) {  
                int compareOrderId = x.OrderID.CompareTo(y.OrderID);  
    
                if (OrderIdDescending) {  
                    compareOrderId = -compareOrderId;  
                }  
                return compareOrderId;  
            }  
    
            if (DateDescending) {  
                compareDate = -compareDate;  
            }  
            return compareDate;  
        }  
    
        public bool DateDescending { get; set; }  
        public bool OrderIdDescending { get; set; }  
    }  
    

    In this scenario, you must instantiate it as MyOrderingClass explicitly( rather then IComparer )
    in order to set its sorting properties :

    MyOrderingClass comparer = new MyOrderingClass();  
    comparer.DateDescending = ...;  
    comparer.OrderIdDescending = ...;  
    orderList.Sort(comparer);  
    
    0 讨论(0)
提交回复
热议问题