开发者

Reordering a collection what am I doing wrong?

I need to reorder a collection The fi开发者_运维百科nal 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?


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


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

Need to compare not assign the "ThenBy"


You should use == not = in ThenBy


How about this?

IOrderedEnumerable<OrderLineItem> orderedItemList= 

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


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 put those where both criteria are true first, and all others after. If I'm misinterpreting your specification, please disregard.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜