【问题标题】:Order by descending based on condition根据条件降序排列
【发布时间】:2010-04-15 07:26:58
【问题描述】:

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

    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# asp.net linq linq-to-sql linq-to-entities


    【解决方案1】:

    我认为您不能将条件放入更大的查询中,但您可以将其分离到另一个 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>();
    

    【讨论】:

      【解决方案2】:

      你可以用

      进一步减少它
      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>();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-28
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 2021-02-01
        • 1970-01-01
        相关资源
        最近更新 更多