Order by descending based on condition

我怕爱的太早我们不能终老 提交于 2019-12-23 10:17:06

问题


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;
        }
    }

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2643383/order-by-descending-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!