Sort Descending by Condition

I want to write a LINQ to Entity query that executes an ascending or descending order based on an input parameter. Is there any way for this. Below is my code. Please suggest.

public List<Hosters_HostingProviderDetail> GetPendingApproval(SortOrder sortOrder) { List<Hosters_HostingProviderDetail> returnList = new List<Hosters_HostingProviderDetail>(); int pendingStateId = Convert.ToInt32(State.Pending); //If the sort order is ascending if (sortOrder == SortOrder.ASC) { var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId orderby e.HostingProviderName ascending select e; returnList = hosters.ToList<Hosters_HostingProviderDetail>(); return returnList; } else { var hosters = from e in context.Hosters_HostingProviderDetail where e.StateID == pendingStateId orderby e.HostingProviderName descending select e; returnList = hosters.ToList<Hosters_HostingProviderDetail>(); return returnList; } } 
+4
source share
2 answers

I don't think you can put a condition in a larger query, but what you could do is split it into another C # statement, for example:

 // Common code: var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId; // The difference between ASC and DESC: hosters = (sortOrder == SortOrder.ASC ? hosters.OrderBy(e => e.HostingProviderName) : hosters.OrderByDescending(e => e.HostingProviderName)); // More common code: returnList = hosters.ToList<Hosters_HostingProviderDetail>(); 
+7
source

You can reduce it one step further with

 var hosters = from e in context.Hosters_HostingProviderDetail where e.ActiveStatusID == pendingStateId select e; if (sortOrder == SortOrder.ASC) hosters = hosters.OrderBy(e => e.HostingProviderName); else hosters = hosters.OrderByDescending(e => e.HostingProviderName); return hosters.ToList<Hosters_HostingProviderDetail>(); 
+2
source

Source: https://habr.com/ru/post/1307004/


All Articles