Tom Squires
Tom Squires

Reputation: 9286

Orderby in generic list

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);

Upvotes: 3

Views: 3107

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500225

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.)

Upvotes: 12

philipproplesch
philipproplesch

Reputation: 2127

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

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

Upvotes: 7

Related Questions