LINQ multiple order by

你。 提交于 2019-11-28 08:44:29

问题


I have created a function that has the follwing parameter:

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

This parameter is optional, If it is filled it should create a order by and than by constuction for me, so that I can order the result on the SQL server.

I tried:

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

But the than By is not reconized. Does someone know how I can solve this problem?


I changed it to .ThenBy() but this is only allowed directly after the .OrderBy() and not on a IOrderedQueryable

so temp = catalogProducts.OrderBy(func).ThenBy(func); is allowed but temp = catalogProducts.OrderBy(func); temp = temp.ThenBy(func); issn't

Any other suggestions?


回答1:


Two problems; firstly, ThanBy should be ThenBy; secondly, ThenBy is only available on the generic type, IOrderedQueryable<T>.

So change to:

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

and you should be sorted.




回答2:


try this

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



回答3:


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

This will be OK.



来源:https://stackoverflow.com/questions/3084671/linq-multiple-order-by

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