Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paging through an IEnumerable

I have an IEnumerable object (IEnumerable<Class>) and I would like to retrieve a specified line from the object. So if I'm on page two I would like to select row two from the IEnumerable object and then pass it on to another class etc.

I'm a bit stuck at the moment, any ideas?

like image 414
Funky Avatar asked Dec 17 '10 15:12

Funky


3 Answers

Look at the functions .Take() and .Skip(). I normally do something like this:

IEnumerable<object> GetPage(IEnumerable<object> input, int page, int pagesize)
{
     return input.Skip(page*pagesize).Take(pagesize);
}
like image 102
Timothy Baldridge Avatar answered Nov 14 '22 02:11

Timothy Baldridge


If I understand your requirements correctly, something like this paging mechanism should work:

int pageSize = 10;
int pageCount = 2;

iEnumerable.Skip(pageSize*pageCount).Take(pageSize);

This example shows 10 rows per page and a page number of 2. So, it will skip to page 2 and take the first row on that page.

like image 21
Randy Minder Avatar answered Nov 14 '22 00:11

Randy Minder


Assuming that pages and rows start at 1, and there is a fixed number of rows per page (say 10), you need to transform the page number and the row to an index as follows:

Page    1  1  1  1  1  1  1  1  1  1  2  2  2  2  2  2  2  2  2  2  3  3  3 ...
Row     1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3 ...
                                         ↓
Index   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...

Code:

int page = 2;
int row = 2;

int rowsPerPage = 10;

IEnumerable<MyClass> source = ...

MyClass result = source.ElementAt((page - 1) * rowsPerPage + (row - 1));

So to get row 2 on page 2, you need to skip the first page (10 elements) and then take the second element (index 1 in that page).

like image 38
dtb Avatar answered Nov 14 '22 01:11

dtb