Published Tuesday, June 19, 2007 6:34 AM by mtaulty

Paging Data in LINQ to SQL

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.

# Link Listing - June 19, 2007 @ Tuesday, June 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

# Link Listing - June 19, 2007 @ Thursday, July 19, 2007 10:53 PM

Link Listing - June 19, 2007

Christopher Steen