好的,我找到了
this,这将允许我这样做:
- public IList<Item> GetItems(string orderbyColumn)
- {
- return _repository.GetItems().OrderBy(orderByColumn).ToList();
- }
这是进行“动态”排序的最佳方式吗?我希望能够将列名作为字符串(和排序方向)传递给我的服务,并让它以正确的方式排序.
解决方法
如果您只是在动态排序之后没有完整的Dynamic-Linq内容,您可以查看我之前写的一篇文章:
click
- public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source,string sortExpression) where TEntity : class
- {
- if (string.IsNullOrEmpty(sortExpression))
- return source; // nothing to sort on
- var entityType = typeof(TEntity);
- string ascSortMethodName = "OrderBy";
- string descSortMethodName = "OrderByDescending";
- string[] sortExpressionParts = sortExpression.Split(' ');
- string sortProperty = sortExpressionParts[0];
- string sortMethod = ascSortMethodName;
- if (sortExpressionParts.Length > 1 && sortExpressionParts[1] == "DESC")
- sortMethod = descSortMethodName;
- var property = entityType.GetProperty(sortProperty);
- var parameter = Expression.Parameter(entityType,"p");
- var propertyAccess = Expression.MakeMemberAccess(parameter,property);
- var orderByExp = Expression.Lambda(propertyAccess,parameter);
- MethodCallExpression resultExp = Expression.Call(
- typeof(Queryable),sortMethod,new Type[] { entityType,property.PropertyType },source.Expression,Expression.Quote(orderByExp));
- return source.Provider.CreateQuery<TEntity>(resultExp);
- }