The following is a function that queries a table (Users) and returns a single page. The main points:
- Query requires a sort by clause
- Function determines how many rows to skip
- Function tells LINQ how many rows to take
List Users by Page
public async Task> List(int page, int recordsPerPage)
{
//primary query
//must have an order by clause
var query = from users in this._DbContext.Users
orderby users.Id
select users;
//how many records should we skip over (ex: page 1, skip over none);
var recordsToSkip = this.Get_RecordsToSkip(page, recordsPerPage);
//skip results, take page size, and return
return await query.Skip(recordsToSkip).Take(recordsPerPage).ToListAsync();
}
Function to Determine How Many Records to Skip
public int Get_RecordsToSkip(int page, int recordsPerPage)
{
int recordsToSkip = 0;
if (page <= 0)
{
page = 1;
}
recordsToSkip = (page * recordsPerPage) - recordsPerPage;
return recordsToSkip;
}