根据条件降序排列 [英] Order by descending based on condition

查看:99
本文介绍了根据条件降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个LINQ to Entity查询,该查询根据输入参数通过升序或降序进行排序,有什么办法吗? 以下是我的代码.请提出建议.

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

推荐答案

我认为您不能将条件放入较大的查询中,但是您可以将其分成另一个C#语句,如下所示:

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

这篇关于根据条件降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆