How do I apply OrderBy on an IQueryable using a st

2019-01-01 00:06发布

public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName)
  where T : EntityObject
{
  var param = Expression.Parameter(typeof(T), "o");
  var body = Expression.PropertyOrField(param,columnName);

  var sortExpression = Expression.Lambda(body, param);
  return query.OrderBy(sortExpression);
}

Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:

var sortExpression = Expression.Lambda<T, TSortColumn>(body, param);

Or

return query.OrderBy<T, TSortColumn>(sortExpression);

I don't think this is possible however as TSortColumn can only be determined during runtime.

Is there a way around this?

8条回答
梦寄多情
2楼-- · 2019-01-01 01:10

You can also use Dynamic Linq

Info here http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

C# download here http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx

Then just add the using Linq.Dynamic; and you automatically get 2 additional extension methods that can be used like this

return query.OrderBy("StringColumnName");
查看更多
泪湿衣
3楼-- · 2019-01-01 01:10

If you are able to add "System.Linq.Dynamic" package then, Too easy without any complication,

fisrt insatll package "System.Linq.Dynamic" from NuGet package manager then try as below as your need,

Ex:

public IQueryable<TEntity> GetWithInclude(Expression<Func<TEntity, bool>> predicate,
                    List<string> sortBy, int pageNo, int pageSize = 12, params string[] include)
        {
            try
            {
                var numberOfRecordsToSkip = pageNo * pageSize;
                var dynamic = DbSet.AsQueryable();

                foreach (var s in include)
                {
                    dynamic.Include(s);
                }
                 return dynamic.OrderBy("CreatedDate").Skip(numberOfRecordsToSkip).Take(pageSize);


            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

Hope this will help

查看更多
登录 后发表回答