How to implement Pagination in an IQuerable in C#?

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 303
The below code will do so

[HttpGet]
[Route("records/EmployeeRecords")]
public List<AccountViewModel> GetDetailEmployee(int pageNumber, int take)
{
var skip = GetSkip(pageNumber, take);

return GetEmployeeRecords().OrderBy(o=>o.EmpID).Skip(skip).Take(take).ToList();
}


The GetSkip function is defined as under

private static int GetSkip(int pageNumber, int take)
{
var skip = (pageNumber - 1) * take;
return skip;
}


And the GetEmployeeRecords() is defined as under

private IQueryable<EmployeeViewModel> GetEmployeeRecords()
{
IQueryable<EmployeeViewModel> empRecords = null;
using (IEmployeeRepository _RepoEmployee = DataAccessAccount.EmployeeRepository)
{
empRecords = new ViewModelDatabase().Employees;
}
return empRecords;
}


The GetEmployeeRecords() is a function that returns an IQueryable.

If the Page number is 1 and take value is 50 and the total records is say 160, then the Skip value will be 0 and take will be 50.
If the Page number is 2 and take value is 50 and the total records is say 160, then the Skip value will be 50 and take will be 50. This indicates that we are requesting from record number 51 to 100.

Hope this helps

Comments or Responses

Login to post response