3

I have a generic list which I form from two other lists. The orderby doesn't seem to be working correctly. BeOrders come first (ordered by date) then BTOrders (ordered by date). Have I missed something obvious? I can't see anything wrong.

orders = new List<DataLayer.OrderStatusItem>();
orders.AddRange(BeOrders);
orders.AddRange(BTOrders);

orders.OrderBy(z => z.ordered);

2 Answers 2

12

Yes, you've missed that OrderBy doesn't order in-place - it returns an ordered sequence:

var inOrder = orders.OrderBy(z => z.ordered);

Or (assuming that orders is of type List<...>:

orders = orders.OrderBy(z => z.ordered).ToList();

Note that this "no side effects" approach is prevalent throughout LINQ - none of the operators change the collection they're called on; they return a view onto that collection of some form (filtered, projected etc).

If you want to sort a List<T> in place you can use List<T>.Sort. (You'll have to specify the ordering in a different way though.)

0
7

OrderBy returns an IOrderedEnumerable<T>, so you have to assign it to a variable:

orders = orders.OrderBy(z => z.ordered);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.