LINQ Paging Data Using Skip and Take operators

By Indranil Chatterjee

We often have the need to display or bind a certain section (page) of data out of the total set of rows in a sequence. However, the filtering here is not based on some condition/predicate. It is something like saying "Give me 2nd set of 3 rows out of the total 10 rows in the sequence". Previously, such needs involved cutom coding but with LINQ, its easy as demonstrated by the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EggHeadApp
{
class Program
{
   static void Main(string[] args)
  {
   int currentPage = 2;
   int pageSize = 3;

   var res = GetPersons().Skip((currentPage - 1) * pageSize).Take(pageSize);
   foreach (var p in res)
    Console.Write(p);
  }

private static IEnumerable<Person> GetPersons()
{
   return new List<Person>
   {
      new Person { Id = 1, Name = "Person1" },
      new Person { Id = 2, Name = "Person2" },
      new Person { Id = 3, Name = "Person3" },
      new Person { Id = 4, Name = "Person4" },
      new Person { Id = 5, Name = "Person5" },
      new Person { Id = 6, Name = "Person6" },
      new Person { Id = 7, Name = "Person7" },
      new Person { Id = 8, Name = "Person8" },
      new Person { Id = 9, Name = "Person9" },
      new Person { Id = 10, Name = "Person10" },
    };
  }
}

public class Person
{
   public int Id { get; set; }
   public string Name { get; set; }

   public override string ToString()
   {
      return string.Format("Id: {0}, Name: {1}{2}", Id, Name, Environment.NewLine);
    }
  }
}

LINQ Paging Data Using Skip and Take operators  (751 Views)