how to apply paging on a list

You can page a list with LINQ, like this:

IList<demodto> GetPage(IList<demodto> list, int page, int pageSize) {
    return list.Skip(page*pageSize).Take(pageSize).ToList();
}

For example, suppose each page has 50 records. To get a third page, call

IList<demodto> thirdPage = GetPage(dataList, 3, 50);

Note, however, that applying paging to data in memory makes very little sense: the idea behind paging is to cut down on the time it takes to retrieve your data from the database, and to save some memory by keeping only a single page, which is not going to happen in your case, because all data is retrieved at once.

In order to make paging worth the effort, you need to move it into the database. Change your method to accept page size and number, and use them to change the SQL to retrieve the list for a single page. Don't forget to force ordering on your sql read, otherwise the same data might appear on different pages. Your SQL needs to be modified to support pagination. This is done differently depending on your database. MS SQL Server solution is described in this answer.


int pagesize = 1000;
int countitens = list1.Count();
int pagecount = countitens % pagesize <= 0 ? countitens / pagesize : (countitens / pagesize) + 1; // for example 10001 itens and page size of 1000 retusn 2 pages
for (int page = 0; page < pagecount; page++)
{
    var itens = list1.Skip(page * pagesize).Take(pagesize).ToList();
}

Or just

var itens = list1.Skip(page-1 * pagesize).Take(pagesize).ToList(); // page-1 if value of page start with 1

Tags:

C#

List