我在我的asp.net 4.0网络应用程序中使用JqGrid,我想要实现列排序。我的问题是我的repo类中的Get方法需要一个Expression>按参数排序的类型:
public IEnumerable<TEntity> Get<TOrderBy>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TOrderBy>> orderBy, int pageIndex, int pageSize, out int totalNumberOfRecords, SortOrder sortOrder = SortOrder.Ascending)
{
IEnumerable<TEntity> list = null;
int numberOfRecordsToSkip = CalculateNumberOfRecordsToSkip(pageIndex, pageSize);
if (sortOrder == SortOrder.Ascending)
{
list = GetQuery().Where(predicate).OrderBy(orderBy).Skip(numberOfRecordsToSkip).Take(pageSize).AsEnumerable().ToList();
}
else
{
list = GetQuery().Where(predicate).OrderByDescending(orderBy).Skip(numberOfRecordsToSkip).Take(pageSize).AsEnumerable().ToList();
}
totalNumberOfRecords = GetQuery().Count(predicate);
return list;
}
当我所知道的是编译时实体的类型时,如何通过表达式创建排序?我希望能够按任何列(或实体属性,如果您愿意)对网格进行排序。
应该按表达式创建排序的方法需要一个参数,即列名:
public Expression<Func<TEntity, TOrderBy>> CreateOrderByExpression(string sortColumn)
{
// I don't know the TOrderBy type before this method is called. I know the TEntity type // so getting the type of the sortColumn is easy.
// But how do I create the Expression<Func<TEntity, TOrderBy>> from here ?
}
因此CreateOrderByExpression方法的结果应该用作参数 在我的repo类中获取方法。
你有什么建议吗?
答案 0 :(得分:1)
您可以使用DynamicLinq库(实际为1.cs文件):
我没有检查过这个,但我确定值得一看:https://nuget.org/packages/DynamicLINQ
编辑:Nugget包的示例:http://weblogs.asp.net/davidfowler/archive/2010/08/19/dynamic-linq-part-2-evolution.aspx (看起来非常好而且容易!)