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

后端 未结 4 1841
一生所求
一生所求 2020-12-23 12:57

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(         


        
相关标签:
4条回答
  • 2020-12-23 13:27

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

     Phrases = bannersPhrases.Select(x=>x.Phrase).Skip(10).Take(10).ToArray()
    
    0 讨论(0)
  • 2020-12-23 13:32

    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
    
    0 讨论(0)
  • 2020-12-23 13:35

    You can use Skip extension method

    Phrases = bannersPhrases.Select(x=>x.Phrase).Skip(10).Take(10).ToArray()
    
    0 讨论(0)
  • 2020-12-23 13:38
    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();
    
    0 讨论(0)
提交回复
热议问题