0

We are using nTiers and I have this list of objects that i need to sort by a property but then by another property,i have the following but i cant figure out how to to the ThenBy, I have seen examples with List<object> but not with TList<object>.

TList<Client> clients = service.GetClientsById(cid);
clients.Sort("ClientOrder");

but then i need to sort it by the ClientName. I saw an example in another post using LINQ, but i cant get this to work like that (example below),which would allow me to do a ThenBy

List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();

You need to call ThenBy<Client> before you call ToList<Client>:

List<Order> sortedList =
    clients.OrderBy(o => o.ClientOrder)
           .ThenBy(o => o.ClientName)
           .ToList();

ThenBy<T> works only on IOrderedEnumerable<T>s IOrderedEnumerable<T>s are the return type from OrderBy<T>, but once you call ToList<T>, it's not an IOrderedEnumerable<T> anymore, but a List<T> and List<T> doesn't implement IOrderedEnumerable<T>.

4

2 回答 2

1

You can use the Comparison class with List.Sort:

clients.Sort(new Comparison<Client>(
    (client1, client2) =>
    {
        // compare dates
        int result = client1.OrderDate.CompareTo(client2.OrderDate);
        // if dates are equal (result = 0)
        if(result == 0)
            // return the comparison of client names
            return client1.ClientName.CompareTo(client2.ClientName);
        else
            // otherwise return dates comparison
            return result;
    })
);

(In the example above, handling null values is skipped but it must be included in a real work).

于 2013-07-25T00:51:39.280 回答
1

您需要在致电ThenBy<Client> 之前致电ToList<Client>

List<Order> sortedList =
    clients.OrderBy(o => o.ClientOrder)
           .ThenBy(o => o.ClientName)
           .ToList();

ThenBy<T>仅适用于sIOrderedEnumerable<T>IOrderedEnumerable<T>from 的返回类型OrderBy<T>,但是一旦您调用ToList<T>,它就不再是IOrderedEnumerable<T>a 了,而是 aList<T>并且List<T>没有实现IOrderedEnumerable<T>

于 2013-07-25T00:46:24.097 回答