How to Sort a List by a property in the object

前端 未结 20 2002
醉梦人生
醉梦人生 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<Order> {
    
        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<Order>
    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.

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

    If you need to sort the list in-place then you can use the Sort method, passing a Comparison<T> delegate:

    objListOrder.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));
    

    If you prefer to create a new, sorted sequence rather than sort in-place then you can use LINQ's OrderBy method, as mentioned in the other answers.

    0 讨论(0)
  • 2020-11-21 08:36
    //Get data from database, then sort list by staff name:
    
    List<StaffMember> staffList = staffHandler.GetStaffMembers();
    
    var sortedList = from staffmember in staffList
                     orderby staffmember.Name ascending
                     select staffmember;
    
    0 讨论(0)
  • 2020-11-21 08:41

    Please let me complete the answer by @LukeH with some sample code, as I have tested it I believe it may be useful for some:

    public class Order
    {
        public string OrderId { get; set; }
        public DateTime OrderDate { get; set; }
        public int Quantity { get; set; }
        public int Total { get; set; }
    
        public Order(string orderId, DateTime orderDate, int quantity, int total)
        {
            OrderId = orderId;
            OrderDate = orderDate;
            Quantity = quantity;
            Total = total;
        }
    }
    
    public void SampleDataAndTest()
    {
        List<Order> objListOrder = new List<Order>();
    
        objListOrder.Add(new Order("tu me paulo ", Convert.ToDateTime("01/06/2016"), 1, 44));
        objListOrder.Add(new Order("ante laudabas", Convert.ToDateTime("02/05/2016"), 2, 55));
        objListOrder.Add(new Order("ad ordinem ", Convert.ToDateTime("03/04/2016"), 5, 66));
        objListOrder.Add(new Order("collocationem ", Convert.ToDateTime("04/03/2016"), 9, 77));
        objListOrder.Add(new Order("que rerum ac ", Convert.ToDateTime("05/02/2016"), 10, 65));
        objListOrder.Add(new Order("locorum ; cuius", Convert.ToDateTime("06/01/2016"), 1, 343));
    
    
        Console.WriteLine("Sort the list by date ascending:");
        objListOrder.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));
    
        foreach (Order o in objListOrder)
            Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);
    
        Console.WriteLine("Sort the list by date descending:");
        objListOrder.Sort((x, y) => y.OrderDate.CompareTo(x.OrderDate));
        foreach (Order o in objListOrder)
            Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);
    
        Console.WriteLine("Sort the list by OrderId ascending:");
        objListOrder.Sort((x, y) => x.OrderId.CompareTo(y.OrderId));
        foreach (Order o in objListOrder)
            Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);
    
        //etc ...
    }
    
    0 讨论(0)
  • 2020-11-21 08:42

    The easiest way I can think of is to use Linq:

    List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();
    
    0 讨论(0)
  • 2020-11-21 08:42

    Using LINQ

    objListOrder = GetOrderList()
                       .OrderBy(o => o.OrderDate)
                       .ToList();
    
    objListOrder = GetOrderList()
                       .OrderBy(o => o.OrderId)
                       .ToList();
    
    0 讨论(0)
提交回复
热议问题