开发者

Order by descending based on condition

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_HostingProviderD开发者_高级运维etail>();
            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;
        }
    }


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>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜