joezen777
joezen777

Reputation: 446

Is it possible to pass an OrderBy expression as an argument?

I'm building a repository framework with NHibernate. Part of my requirements include limiting the number of results returned- or forcing paging. In order for NHibernate to successfully parse the query from the IQueryable expression, it must perform OrderBy or OrderByDescending operations before any .Skip().Take() operation.

This is how my current signature is called.

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

This is the interface signature.

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);

(The include argument is not relevant for the question)

Is it possible to have a signature that would accept something like this as the parameter?

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

Then I would be able to apply this expression within my repository and I would no longer have any limits on the number of orderbys or whether it's orderbydescending or what not.

Thanks

Upvotes: 4

Views: 1605

Answers (1)

Cemafor
Cemafor

Reputation: 1653

The lambda expression is just a function. So you should be able to use Func<IEnumerable<TEntity>,IEnumerable<TEntity>>. You are effectivly wanting to pass in a function that takes in an IEnumerable and give out a different IEnumerable.

Upvotes: 3

Related Questions