Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first 10 records, then next 10, paging using Linq

Tags:

c#

linq

How select first 10 records, Then the next 10, Then the next 10, and so long as the array will not end.

Phrases = bannersPhrases.Select(x=>x.Phrase).Take(10).ToArray()

How get the next 10 records?

like image 815
den den Avatar asked Mar 15 '12 10:03

den den


4 Answers

var total = bannersPhrases.Select(p => p.Phrase).Count();
var pageSize = 10; // set your page size, which is number of records per page

var page = 1; // set current page number, must be >= 1 (ideally this value will be passed to this logic/function from outside)

var skip = pageSize * (page-1);

var canPage = skip < total;

if (!canPage) // do what you wish if you can page no further
   return;

Phrases = bannersPhrases.Select(p => p.Phrase)
             .Skip(skip)
             .Take(pageSize)
             .ToArray();
like image 145
moribvndvs Avatar answered Nov 13 '22 00:11

moribvndvs


If you are doing paging and you just want to skip to a particular page you can use Skip and Take as described in some of the other answers. However, if you want group the entire sequence into chunks of a particular size you can use GroupBy instead. Here is a small example:

var groupSize = 4;
// The characters 'a' - 'z'.
var source = Enumerable.Range(0, 26).Select(i => (Char) ('a' + i));
var groups = source
  .Select((x, i) => new { Item = x, Index = i })
  .GroupBy(x => x.Index/groupSize, x => x.Item);
foreach (var group in groups)
  Console.WriteLine("{0}: {1}", group.Key, String.Join(", ", group));

The output is:

0: a, b, c, d
1: e, f, g, h
2: i, j, k, l
3: m, n, o, p
4: q, r, s, t
5: u, v, w, x
6: y, z
like image 44
Martin Liversage Avatar answered Nov 12 '22 23:11

Martin Liversage


You can use .Skip() .This will return the next 10 items:

 Phrases = bannersPhrases.Select(x=>x.Phrase).Skip(10).Take(10).ToArray()
like image 8
Tsabo Avatar answered Nov 13 '22 01:11

Tsabo


You can use Skip extension method

Phrases = bannersPhrases.Select(x=>x.Phrase).Skip(10).Take(10).ToArray()
like image 5
oleksii Avatar answered Nov 13 '22 00:11

oleksii