How to Sort a List by a property in the object

2018-12-31 02:52发布

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

List<Order> objListOrder = new List<Order>();
GetOrderList(objListOrder); // fill list of orders

Now I want to sort the list based on one property of the Order object, for example I need to sort it by the order date or order id.

How can i do this in C#?

19条回答
若你有天会懂
2楼-- · 2018-12-31 03:27
var obj = db.Items.Where...

var orderBYItemId = obj.OrderByDescending(c => Convert.ToInt32(c.ID));
查看更多
闭嘴吧你
3楼-- · 2018-12-31 03:28

Anybody working with nullable types, Value is required to use CompareTo.

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

查看更多
刘海飞了
4楼-- · 2018-12-31 03:29

To do this without LINQ on .Net2.0:

List<Order> objListOrder = GetOrderList();
objListOrder.Sort(
    delegate(Order p1, Order p2)
    {
        return p1.OrderDate.CompareTo(p2.OrderDate);
    }
);

If you're on .Net3.0, then LukeH's answer is what you're after.

To sort on multiple properties, you can still do it within a delegate. For example:

orderList.Sort(
    delegate(Order p1, Order p2)
    {
        int compareDate = p1.Date.CompareTo(p2.Date);
        if (compareDate == 0)
        {
            return p2.OrderID.CompareTo(p1.OrderID);
        }
        return compareDate;
    }
);

This would give you ascending dates with descending orderIds.

However, I wouldn't recommend sticking delegates as it will mean lots of places without code re-use. You should implement an IComparer and just pass that through to your Sort method. See here.

public class MyOrderingClass : IComparer<Order>
{
    public int Compare(Order x, Order y)
    {
        int compareDate = x.Date.CompareTo(y.Date);
        if (compareDate == 0)
        {
            return x.OrderID.CompareTo(y.OrderID);
        }
        return compareDate;
    }
}

And then to use this IComparer class, just instantiate it and pass it to your Sort method:

IComparer<Order> comparer = new MyOrderingClass();
orderList.Sort(comparer);
查看更多
柔情千种
5楼-- · 2018-12-31 03:31

An improved of Roger's version.

The problem with GetDynamicSortProperty is that only get the property names but what happen if in the GridView we use NavigationProperties? it will send an exception, since it finds null.

Example:

"Employee.Company.Name; " will crash... since allows only "Name" as a parameter to get its value.

Here's an improved version that allows us to sort by Navigation Properties.

public object GetDynamicSortProperty(object item, string propName)
    {
        try
        {                 
            string[] prop = propName.Split('.'); 

            //Use reflection to get order type                   
            int i = 0;                    
            while (i < prop.Count())
            {
                item = item.GetType().GetProperty(prop[i]).GetValue(item, null);
                i++;
            }                     

            return item;
        }
        catch (Exception ex)
        {
            throw ex;
        }


    } 
查看更多
查无此人
6楼-- · 2018-12-31 03:35

From performance point of view the best is to use a sorted list so that data is sorted as it is added to result. Other approaches need at least one extra iteration on data and most create a copy of data so not only performance but memory usage will be affected too. Might not be an issue with couple of hundreds of elements but will be with thousands, especially in services where many concurrent requests may do sorting at the same time. Have a look at System.Collections.Generic namespace and choose a class with sorting instead of List.

And avoid generic implementations using reflection when possible, this can cause performance issues too.

查看更多
永恒的永恒
7楼-- · 2018-12-31 03: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;
查看更多
登录 后发表回答