Overriding the collection, what am I doing wrong?

I need to reorder the collection. The end result should be that all the elements in the collections that have the property One> 0 and PropertyTwo = 0 should be the first and then the rest should follow

I did the following, but I'm 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?

+4
source share
5 answers

You order your collection by comparing what your lambdas return, i.e. logical values. true 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 predicates:

 var orderedItems = OrderList.Cast<OrderLineItem>() .OrderBy(x => x.PropertyOne <= 0) .ThenBy(x => x.PropertyTwo != 0); 
+10
source
 var orderedList = OrderList.Cast<OrderLineItem>() .OrderBy(x => x.PropertyOne > 0) .ThenBy(x=> x.PropertyTwo == 0); 

You need to compare not assigning "ThenBy"

+1
source

You should use == not = in ThenBy

0
source

How about this?

 IOrderedEnumerable<OrderLineItem> orderedItemList= OrderList.Cast<OrderLineItem>() .OrderBy(x => (x.PropertyOne > 0 && x.PropertyTwo == 0) ? 0 : 1); 
0
source

Are you looking for something like this?

 IOrderedEnumerable<OrderLineItem> orderedItemList= OrderList.Cast<OrderLineItem>() .OrderBy(x => (x.PropertyOne > 0 && x.PropertyTwo == 0) ? 0 : 1); 

This will lead to the fact that both criteria will be true first, and all the rest after. If I misinterpreted your specification, please ignore it.

0
source

All Articles