Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 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)
                    then if( x.StatusId == 3) 
                          then order by x.ReserveDate
                     else
                          then order by descending x.LastUpdateDate

How can i do this?

like image 867
ahmad-r Avatar asked Jul 31 '17 10:07

ahmad-r


People also ask

How do I sort by descending in Entity Framework?

Use OrderByDescending to sort in Descending order. . ToList(); Use ThenBy or ThenByDescending clause to sort the results on multiple fields.

How do I get data in descending order in Linq?

OrderByDescending operator is used to rearranging the elements of the given sequence in descending order. It does not support query syntax in C# and VB.Net.

How do I sort data in Entity Framework?

Add sorting functionality to the Index method The query string value is provided by ASP.NET MVC as a parameter to the action method. The parameter is a string that's either "Name" or "Date", optionally followed by an underscore and the string "desc" to specify descending order. The default sort order is ascending.


1 Answers

You can do this in a single OrderBy, for example:

var results = q.OrderByDescending(x => 
    x.StatusId == 3 ? x.ReserveDate : x.LastUpdateDate)
like image 105
DavidG Avatar answered Sep 23 '22 09:09

DavidG