下面的 C# 代码中想通过方法参数传入 OrderBy,请问如何实现?
public async Task<List<T>> GetBlogSites<T>(
int pageIndex,
int pageSize,
<?> orderBy)
{
return await _blogSiteRepository.GetValidBlogs()
// 如何通过参数传入OrderBy
.OrderBy(x => x.LastPublished)
.Page(pageIndex, pageSize)
.ProjectToType<T>()
.ToListAsync();
}
通过 Func<IQueryable<BlogSite>, IOrderedQueryable<BlogSite>>
解决了
public async Task<List<T>> GetBlogSites<T>(
int pageIndex,
int pageSize,
Func<IQueryable<BlogSite>, IOrderedQueryable<BlogSite>> orderBy)
{
var query = _blogSiteRepository.GetValidBlogs();
query = orderBy.Invoke(query);
return await query.Page(pageIndex, pageSize)
.ProjectToType<T>()
.ToListAsync();
}
参考 How to use Func with IQueryable that returns IOrderedQueryable