Subin Jacob
Subin Jacob

Reputation: 4864

How to Sort List<> with property of a user defined object?

I have a List<OrderTime> with OrderTime as shown below

public class OrderTime
    {
        public string OrderId { get; set; }
        public DateTime StarTime { get; set; }
        public DateTime EndTime { get; set; }
    }

I want to sort this list in ascending order of DateTime StarTime. I can do it with bubble sorting, but want to know is there any c# built in methods

Upvotes: 2

Views: 746

Answers (2)

Thomsen
Thomsen

Reputation: 773

You'll want to use

lst.Sort((x, y) => x.StarTime.CompareTo(y.StarTime));

Remember that using lst.OrderBy().ToList() will create a new instance of List<>, probably hurting performance.

Doc: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

Upvotes: 1

John Woo
John Woo

Reputation: 263723

you can use LINQ

List<OrderTime> _orders = new List<OrderTime>();
// _orders.Add(...);
var _result = _orders.OrderBy(x  => x.StarTime);

Upvotes: 7

Related Questions