Paging via IEnumerable

I have an IEnumerable ( IEnumerable<Class> ) object, and I would like to get the specified string from the object. So if I am on the second page, I would like to select the second line from the IEnumerable object, and then pass it to another class, etc.

I'm a little stuck right now, any ideas?

+4
source share
4 answers

Take a look at the .Take() and .Skip() functions. Usually I do something like this:

 IEnumerable<object> GetPage(IEnumerable<object> input, int page, int pagesize) { return input.Skip(page*pagesize).Take(pagesize); } 
+8
source

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

 int pageSize = 10; int pageCount = 2; iEnumerable.Skip(pageSize*pageCount).Take(1); 

This example shows 10 lines per page and page number 2. Thus, it will go to page 2 and take the first line on this page.

+2
source

Assuming pages and lines start with 1, and there is a fixed number of lines per page (say 10), you need to convert the page number and line into 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 on this page).

0
source

I have implemented a dynamic solution in vb.net, hopefully useful:

  <Runtime.CompilerServices.Extension()> Public Function Paginate(Of T As {Class})(source As T, skip As Integer, take As Integer) As T If source IsNot Nothing AndAlso TypeOf source Is IEnumerable Then Dim chunk = (From c In DirectCast(source, IEnumerable)).Skip(skip).Take(take).ToList If chunk.Count = 0 Then Return Nothing Return AutoMapper.Mapper.Map(chunk, GetType(T), GetType(T)) End If Return source End Function 
0
source

Source: https://habr.com/ru/post/1332523/


All Articles