开发者

Orderby in generic list

开发者 https://www.devze.com 2023-04-01 20:21 出处:网络
I have a generic l开发者_高级运维ist 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

I have a generic l开发者_高级运维ist 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);


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消