问题
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();
回答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).
回答2:
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>
.
来源:https://stackoverflow.com/questions/17847112/sorting-tlistobject-ntiers-with-thenby