Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering a collection what am I doing wrong?

I need to reorder a collection The final results should be that all the items in the collections that have propertyOne > 0 and PropertyTwo=0 should be first and then the others should follow

I have done the following but I am not sure why it does not work!

IOrderedEnumerable<OrderLineItem> orderedItemList= 

OrderList.Cast<OrderLineItem>()
      .OrderBy(x => x.PropertyOne > 0)
      .ThenBy(x => x.PropertyTwo == 0);

Any Suggestions?

like image 308
user9969 Avatar asked Dec 22 '22 21:12

user9969


1 Answers

You're ordering your collection by comparing what your lambdas return, i.e. boolean values. true is greater than false. Therefore, you need to either use OrderByDescending():

var orderedItems
    = OrderList.Cast<OrderLineItem>()
               .OrderByDescending(x => x.PropertyOne > 0)
               .ThenByDescending(x => x.PropertyTwo == 0);

Or invert your predicates:

var orderedItems
    = OrderList.Cast<OrderLineItem>()
               .OrderBy(x => x.PropertyOne <= 0)
               .ThenBy(x => x.PropertyTwo != 0);
like image 90
Frédéric Hamidi Avatar answered Dec 24 '22 10:12

Frédéric Hamidi