Search⌘ K
AI Features

Paging with LINQ

Explore how to implement paging in LINQ by using Skip and Take methods to display product data page by page. Understand the importance of ordering data before paging to ensure consistent results in queries and learn to navigate pages interactively, improving data handling in applications.

Implement paging using Skip and Take methods

Let’s see how we could implement paging using the Skip and Take extension methods:

Step 1: In Program.Functions.cs, add a method to output to the console a table of products passed as an array, as shown in the following code:

C#
static void OutputTableOfProducts(Product[] products,
int currentPage, int totalPages)
{
string line = new('-', count: 73);
string lineHalf = new('-', count: 30);
WriteLine(line);
WriteLine("{0,4} {1,-40} {2,12} {3,-15}",
"ID", "Product Name", "Unit Price", "Discontinued");
WriteLine(line);
foreach (Product p in products)
{
WriteLine("{0,4} {1,-40} {2,12:C} {3,-15}",
p.ProductId, p.ProductName, p.UnitPrice, p.Discontinued);
}
WriteLine("{0} Page {1} of {2} {3}",
lineHalf, currentPage + 1, totalPages + 1, lineHalf);
}

Note: As usual in computing, our code we will start counting from zero, so we need to add one to ...