Linq-to-Entities Dynamic sorting

前端 未结 5 659
无人共我
无人共我 2021-02-04 03:51

This is my query, how can I use string as orderby parameter?

string sortColumn=\"Title\";

var  items = (from ltem in ctxModel.Items
              where ltem.Ite         


        
5条回答
  •  暖寄归人
    2021-02-04 04:36

    I use this helper:

    public static class OrderExt
    {
        private static IOrderedQueryable Order(this IQueryable source, string propertyName, SortDirection descending, bool anotherLevel = false)
        {
            var param = Expression.Parameter(typeof(T), string.Empty);
            var property = Expression.PropertyOrField(param, propertyName);
            var sort = Expression.Lambda(property, param);
    
            var call = Expression.Call(
                typeof (Queryable),
                (!anotherLevel ? "OrderBy" : "ThenBy") +
                (descending == SortDirection.Descending ? "Descending" : string.Empty),
                new[] {typeof (T), property.Type},
                source.Expression,
                Expression.Quote(sort));
    
            return (IOrderedQueryable)source.Provider.CreateQuery(call);
        }
    }
    

    to call the helper, eg do this:

    string sort = HttpContext.Current.Request.QueryString["sort"];
    var products = _productRepository.OrderBy(sort, SortDirection.Ascending);
    

提交回复
热议问题