How to Sort a List by a property in the object

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

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

    public class MyOrderingClass : IComparer {  
        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);  
    

提交回复
热议问题