Порядок путем убывания на основе условия

Я хочу записать LINQ в запрос Объекта, который действительно заказывает путем возрастания или убывания на основе входного параметра, там любой путь к этому. Следующее является моим кодом. Предложите.

    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;
        }
    }
5
задан Vinay Kumar Chella 15 April 2010 в 07:26
поделиться

2 ответа

Я не думаю, что вы можете поместить условие в более крупный запрос, но вы могли бы разделить его на другой оператор C #, например:

// 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
ответ дан 13 December 2019 в 22:04
поделиться

Вы можете еще больше сократить его с помощью

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>();
3
ответ дан 13 December 2019 в 22:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: