Published
Tuesday, June 19, 2007 6:34 AM
by
mtaulty
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.