Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition in lambda expression order by

I have 2 Lists that return the same Item . <foo> has the propriety orderType that is 0 for the first list and 1 for the second one On the first list I do filtering and I have to add the items from the second list to the result that is limited by pagination. Basically this is my final Query :

var listFoo= QueryList1.Concat(QueryList2);  //(IQueriable)
List<foo> listFoo =listFoo.OrderByDescending(r => r.ID)
                          .ThenBy(d =>d.orderType)
                          .Skip((currentPageIndex - 1) * pageSize)
                          .Take(pageSize)
                          .ToList();

This works great because list 1 works as main item and list 2 works as details for first list. Also my filters should work only on the first list. But the problem comes here. How can I order the second list only by date. I need to list the details ordered by date. Basically i need something like :

List<foo> listFoo =listFoo.OrderByDescending(r => r.ID)
                          .ThenBy(d =>d.orderType)
                          .ThenBy(x=>(x.ordertype==1)?x.Date)
                          .Skip((currentPageIndex - 1) * pageSize)
                          .Take(pageSize)
                          .ToList();

Edit :

List 1 : 
id =1,ordertype=0,Date = new DateTime(1950,1,4),  [0]
id =2,ordertype=0,Date = new DateTime(1950,2,1)   [1]
List 2 :
id =1,ordertype=1,Date = new DateTime(1950,1,5),  [2]
id =1,ordertype=1,Date = new DateTime(1950,1,2),  [3]
id =1,ordertype=1,Date = new DateTime(1950,1,3),  [4]
id =1,ordertype=1,Date = new DateTime(1950,1,4)   [5]

This should be ordered as follows : 
[0],[3],[4],[5],[2],[1]
like image 837
Mihai Labo Avatar asked Dec 11 '25 07:12

Mihai Labo


1 Answers

It looks like you're missing the last part of the ternary operator:

listFoo = listFoo.OrderByDescending(r => r.ID)
                           .ThenBy(d =>d.orderType)
                           .ThenBy(x => (x.ordertype==1) ? x.Date : DateTime.MinValue)
                           .Skip((currentPageIndex - 1) * pageSize)
                           .Take(pageSize)
                           .ToList();

If you don't care about the order if ordertype is something other than 1 then the else condition is arbitrary.

like image 50
D Stanley Avatar answered Dec 13 '25 22:12

D Stanley