【问题标题】:LINQ multiple order byLINQ 多重排序
【发布时间】:2010-06-21 12:38:32
【问题描述】:

我创建了一个具有以下参数的函数:

List<Expression<Func<CatalogProduct, bool>>> orderBy = null

这个参数是可选的,如果它被填写,它应该为我创建一个订单,而不是构建,这样我就可以在SQL服务器上订购结果。

我试过了:

            IOrderedQueryable temp = null;
            foreach (Expression<Func<CatalogProduct, bool>> func in orderBy)
            {
                if (temp == null)
                {
                    temp = catalogProducts.OrderBy(func);
                }
                else
                {
                    temp = temp.ThanBy(func);
                }
            }

但是比 By 没有被重新识别。有人知道我该如何解决这个问题吗?


我将它更改为 .ThenBy() 但这仅允许在 .OrderBy() 之后直接使用,而不是在 IOrderedQueryable 上

所以 temp = catalogProducts.OrderBy(func).ThenBy(func);是允许的,但 temp = catalogProducts.OrderBy(func); temp = temp.ThenBy(func);不是

还有其他建议吗?

【问题讨论】:

  • 这是英文使用错误,不是编程错误!
  • 查看更新后的答案。
  • 来自 Jon 的评论,从您现在已删除的答案中重新发布:“在 IOrderedQueryable 上允许使用 ThenBy;在普通 IQueryable 上不允许使用。您确定您已正确声明 temp”跨度>

标签: c# linq .net-4.0 sql-order-by


【解决方案1】:

两个问题;首先,ThanBy 应该是ThenBy;其次,ThenBy 仅适用于 generic 类型,IOrderedQueryable&lt;T&gt;

所以改成:

        IOrderedQueryable<CatalogProduct> temp = null;
        foreach (Expression<Func<CatalogProduct, bool>> func in orderBy) {
            if (temp == null) {
                temp = catalogProducts.OrderBy(func);
            } else {
                temp = temp.ThenBy(func);
            }
        }

你应该被排序。

【讨论】:

    【解决方案2】:

    试试这个

       IOrderedQueryable temp = null; 
       foreach (Expression<Func<CatalogProduct, bool>> func in orderBy) 
        { 
          if (temp == null) 
            { 
              temp = catalogProducts.OrderBy(func);
            } 
            else
            { 
              temp = temp.OrderBy(func); 
            } 
         }
    

    【讨论】:

    • 每次都会重新排序从头开始。对于多个订单,你真的应该使用ThenBy
    • 调用第二个OrderBy 将根据具体实现以相反的顺序进行排序,仅按最后一个排序。
    • @Jon - 不一定相当;请记住,LINQ 排序是稳定的,所以这只是颠倒排序顺序。
    • @Marc:是的。不过,这基本上不是正确的方法:)
    【解决方案3】:
            foreach (Expression<Func<CatalogProduct, bool>> func in orderBy)
            {
                catalogProducts = catalogProducts.OrderBy(func);
            }
    

    这样就好了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2012-04-22
      相关资源
      最近更新 更多