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?
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);
}
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With