Mike Taulty's Blog
Bits and Bytes from Microsoft UK
Paging Data in LINQ to SQL

Blogs

Mike Taulty's Blog

Elsewhere

I saw a question over here about "How do I implement paging of data in LINQ to SQL". For me, this is one of the nice things about LINQ to SQL so I thought I'd drop it into a post (it's pretty intuitive).

We can do something like;

   NorthwindDataContext ctx = 
      new NorthwindDataContext("server=.;database=northwind");

    ctx.Log = Console.Out;

    var query = from c in ctx.Customers
                orderby c.CustomerID descending
                select c;

    Console.WriteLine("Enter page size");
    int pageSize = int.Parse(Console.ReadLine());

    while (true)
    {
      Console.WriteLine("Enter page number");
      int pageNumber = int.Parse(Console.ReadLine());

      var thisQuery = 
        query.Skip(pageNumber * pageSize).Take(pageSize);

      Console.WriteLine("Page {0} of data", pageNumber);

      Console.ForegroundColor = ConsoleColor.Yellow;

      List<Customer> customers = thisQuery.ToList();

      Console.ResetColor();
 
      foreach (Customer c in customers)
      {
        Console.WriteLine(c.CustomerID);
      }
    }

 

Or something like that anyway. Note that the ToList is only really there so that I can easily log out the SQL being generated in yellow to the console before writing out the data.


Posted Tue, Jun 19 2007 6:34 AM by mtaulty

Comments

Christopher Steen wrote Link Listing - June 19, 2007
on Tue, Jun 19 2007 7:38 PM
Accessing and Updating Data in ASP.NET 2.0: Deleting Data [Via: ] Adobe AIR Bus Tour [Via: Dion Almaer...
Christopher Steen wrote Link Listing - June 19, 2007
on Thu, Jul 19 2007 10:53 PM
Link Listing - June 19, 2007