I want to write a LINQ to Entity query which does order by ascending or descending based on input parameter, Is there any way for that. Following is the 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;
}
}
Descending Order MeaningIf the information is sorted from highest to lowest, it is said to be in descending order. For example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 are arranged in descending order. In other words, if the numbers are arranged from the largest to the smallest number, it is said to be in descending order.
Descending order is the opposite of ascending order, from lowercase z to uppercase A for character types, and from highest to lowest for numeric data types. DATE and DATETIME data is sorted from latest to earliest, and INTERVAL data is ordered from longest to shortest span of time.
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
You can use the WHERE clause with or without the ORDER BY statement.
I don't think you can put a condition into the larger query, but what you could do is separate it into another C# statement, like this:
// 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>();
You could reduce it a 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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With