How to Sort a List by a property in the object

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

    You can do something more generic about the properties selection yet be specific about the type you're selecting from, in your case 'Order':

    write your function as a generic one:

    public List GetOrderList(IEnumerable orders, Func propertySelector)
            {
                return (from order in orders
                        orderby propertySelector(order)
                        select order).ToList();
            } 
    

    and then use it like this:

    var ordersOrderedByDate = GetOrderList(orders, x => x.OrderDate);
    

    You can be even more generic and define an open type for what you want to order:

    public List OrderBy(IEnumerable collection, Func propertySelector)
            {
                return (from item in collection
                        orderby propertySelector(item)
                        select item).ToList();
            } 
    

    and use it the same way:

    var ordersOrderedByDate = OrderBy(orders, x => x.OrderDate);
    

    Which is a stupid unnecessary complex way of doing a LINQ style 'OrderBy', But it may give you a clue of how it can be implemented in a generic way

提交回复
热议问题