是否可以将OrderBy表达式作为参数传递?

时间:2013-07-02 18:59:50

标签: c# linq lambda

我正在使用NHibernate构建一个存储库框架。我的部分要求包括限制返回的结果数量或强制分页。为了让NHibernate成功地从IQueryable表达式解析查询,它必须在任何.Skip()。Take()操作之前执行OrderBy或OrderByDescending操作。

这是我当前签名的调用方式。

var actualExerciseJournals = repo.GetAll( pageIndex: pageNum++, recordsPerPage: 250, orderByFirst: exerciseJournal => exerciseJournal.JOURNALDATE, orderBySecond: exerciseJournal => exerciseJournal.MEMBERID);

这是界面签名。

IEnumerable<TEntity> GetAll(int pageIndex, int recordsPerPage, Expression<Func<TEntity, object>> orderByFirst, Expression<Func<TEntity, object>> orderBySecond, Expression<Func<TEntity, object>> orderByThird, Expression<Func<TEntity, object>> orderByFourth, params Expression<Func<TEntity, object>>[] include);

(include参数与问题无关)

是否可以使用可接受此类参数的签名?

var actualExerciseJournals = repo.GetAll(pageIndex: 0, recordsPerPage: 250, collectionToOrder => collectionToOrder.OrderBy(x => x.JOURNALDATE).ThenBy(y => y.MEMBERID));

然后我可以在我的存储库中应用这个表达式,我将不再对orderbys的数量有任何限制,或者它是orderbydecending还是不是。

由于

1 个答案:

答案 0 :(得分:3)

lambda表达式只是一个函数。所以你应该可以使用Func<IEnumerable<TEntity>,IEnumerable<TEntity>>。您有效地希望传递一个函数,该函数包含IEnumerable并提供不同的IEnumerable