我正在尝试通过传递给我的控制器sortByColumn
的字符串参数来实现对数据库结果进行排序的动态方式,但我无法看到如何更改OrderBy
以允许此操作。我想我需要某种评估功能?还有更好的方法吗?
public ViewResult List(int page = 1, string? sortByColumn = null)
{
JamesListViewModel model = new JamesListViewModel
{
James = repository.James
//.OrderBy(s => s.Name)
.OrderBy(s => s.sortByColumn) // This line is junk :(
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.James.Count()
}
};
return View(model);
}
答案 0 :(得分:1)
如果没有使用肯定有用的Dynamic LINQ,您可以构建一个简单的switch
语句,其中涵盖您计划排序的James
的所有列,如下所示:
var james = repository.James;
switch (sortByColumn)
{
case "Name": james = james.OrderBy(s => s.Name); break;
case "Age": james = james.OrderBy(s => s.Age); break;
case "Strength": james = james.OrderBy(s => s.Strength); break;
// No default: if sortByColumn is null or unknown, the result is unordered
}
JamesListViewModel model = new JamesListViewModel
{
James = james
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = repository.James.Count()
}
};
答案 1 :(得分:1)
你可以用反射来做,
James = repository.James
.OrderBy(s =>s.GetType().GetProperty(sortByColumn).GetValue(s,null))
.Skip((page - 1) * PageSize)
.Take(PageSize)
答案 2 :(得分:0)
您可以执行以下操作
public IEnumerable GetJames(int page = 1, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,)
{
var query = repository.James;
//other stuff
if (orderBy != null)
{
return orderBy(query).ToList();
}
}
并像
一样使用它public ActionView List()
{
var model = GetJames(orderBy: q => q.OrderBy(d => d.Name));
}
上面的代码不起作用它只是给你一个关于你可以做什么的背景。