B.Mick
B.Mick

Reputation: 37

Pass Where and Orderby Clause using Func for Generic Method

I have Generic Method for Pagination and i want to pass Where clause and order by clause. Is there a way to pass both at same. Thank you

public TableResponse<T> GetPagination<T>(Func<T, bool> filterslambda, Filters filter) where T: class
{
 var query = db.Set<T>().Where(filterslambda).AsQueryable();
}

Here I m calling my generic method

GetPagination<Employee>(x => x.IsActive == true ,filter); <------ Here i want to pass order by after where clause is performed..

Upvotes: 1

Views: 869

Answers (2)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

You can use IOrderedQueryable like below

public TableResponse<T> GetPagination<T>(Func<T, bool> filterslambda, Filters filter, IOrderedQueryable<T>> orderBy = null) where T: class
{
  var query = db.Set<T>().Where(filterslambda).AsQueryable();
  return orderBy != null ? orderBy(query) : query;
}

GetPagination<Employee>(x => x.IsActive == true ,filter, x => x.OrderBy(x => x.Id));

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81533

You are nearly there

public TableResponse<T> GetPagination<T,Tkey>(Func<T, bool> predicate, Func<T, Tkey> selector) 
   where T: class
{
    var query = db.Set<T>().Where(predicate).OrderBy(selector);
}

Upvotes: 3

Related Questions