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

Mike's Badges

Follow on Twitter
View mike's profile on slideshare
Add to Technorati Favorites
CW Blog Awards

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
(C) Mike Taulty, 2009. All rights reserved. The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Inappropriate comments will be deleted at the authors discretion. All code samples are provided "AS IS" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems