Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by descending by row field in query

I want to write a EF query which does order by ascending or descending based on condition. Following is the my pseudo code:

      var result= q.OrderByDescending(x => x.StatusId == 3)
                         if( x.StatusId == 3) 
                              then order by x.ReserveDate
                         if( x.StatusId != 3 ) 
                              then order by descending x.LastUpdateDate

How can i do this?

Update

This is not same as q = condition ? q.OrderBy(..) : q.OrderByDescending(..) as marked in referenced duplicate question, sorting order differs based on value within the row instead of a flag outside query.

like image 953
ahmad-r Avatar asked Nov 22 '25 16:11

ahmad-r


1 Answers

You can supply complex expressions in OrderBy...

// you might have to give bounding start,end for
// for this query to work correctly...

var end = DateTime.Now;
var start = end.AddYears(-100);

var result = q.OrderBy( 
               x => x.StatusId == 3 ?  

               // this will sort by in ascending order 
               DbFunctions.DiffDays(x.ReserveDate, start) :

               // this will sort in descending order
               DbFunctions.DiffDays(end, x.LastUpdateDate) );

SQL Generated will be

SELECT 
    ...
    ...
    FROM ( SELECT CASE 
        WHEN ([Extent2].[StatusId ] = 3) 
            THEN DATEDIFF (day, @p__linq__0, [Extent1].[ReserveDate]) 
        ELSE 
            DATEDIFF (day, [Extent1].[LastUpdateDate], @p__linq__1) 
        END AS [C1] 
        FROM  [dbo].[Table] AS [Extent1]
    )  AS [Project1]
    ORDER BY [Project1].[C1]
like image 78
Akash Kava Avatar answered Nov 25 '25 05:11

Akash Kava