How to Sort a List by a property in the object

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

    A Classical Object Oriented Solution

    First I must genuflect to the awesomeness of LINQ.... Now that we've got that out of the way

    A variation on JimmyHoffa answer. With generics the CompareTo parameter becomes type safe.

    public class Order : IComparable {
    
        public int CompareTo( Order that ) {
            if ( that == null ) return 1;
            if ( this.OrderDate > that.OrderDate) return 1;
            if ( this.OrderDate < that.OrderDate) return -1;
            return 0;
        }
    }
    
    // in the client code
    // assume myOrders is a populated List
    myOrders.Sort(); 
    

    This default sortability is re-usable of course. That is each client does not have to redundantly re-write the sorting logic. Swapping the "1" and "-1" (or the logic operators, your choice) reverses the sort order.

提交回复
热议问题