How to Sort a List by a property in the object

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

    Doing it without Linq as you said:

    public class Order : IComparable
    {
        public DateTime OrderDate { get; set; }
        public int OrderId { get; set; }
    
        public int CompareTo(object obj)
        {
            Order orderToCompare = obj as Order;
            if (orderToCompare.OrderDate < OrderDate || orderToCompare.OrderId < OrderId)
            {
                return 1;
            }
            if (orderToCompare.OrderDate > OrderDate || orderToCompare.OrderId > OrderId)
            {
                return -1;
            }
    
            // The orders are equivalent.
            return 0;
        }
    }
    

    Then just call .sort() on your list of Orders

提交回复
热议问题