Search code examples
c#.netlinqpaging

Paging with LINQ for objects


How would you implement paging in a LINQ query? Actually for the time being, I would be satisfied if the sql TOP function could be imitated. However, I am sure that the need for full paging support comes up sooner later anyway.

var queryResult = from o in objects
                  where ...
                  select new
                      {
                         A = o.a,
                         B = o.b
                      }
                   ????????? TOP 10????????

Solution

  • You're looking for the Skip and Take extension methods. Skip moves past the first N elements in the result, returning the remainder; Take returns the first N elements in the result, dropping any remaining elements.

    See Microsoft's documentation for more information on how to use these methods:
    https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/return-or-skip-elements-in-a-sequence

    If your pageNumber starts at 0 (decrease per 1 as suggested in the comments), you could do it like this:

    int numberOfObjectsPerPage = 10;
    var queryResultPage = queryResult
      .Skip(numberOfObjectsPerPage * pageNumber)
      .Take(numberOfObjectsPerPage);
    

    If pageNumber starts at 1 (as suggested by @Alvin), then you coudld o it like this:

    int numberOfObjectsPerPage = 10;
    var queryResultPage = queryResult
      .Skip(numberOfObjectsPerPage * (pageNumber - 1))
      .Take(numberOfObjectsPerPage);