LINQ in Practice · Lesson 10

Paging a stable sequence

Apply a page size after deciding the ordering.

How it works

Skip and Take express a window over an ordered sequence. This example uses a zero-based page index of one and a page size of three, so it skips the first three values and requests the next three. Order the source before paging whenever page contents must be predictable. Repeatedly paging a changing data source can still shift items between pages; stable sorting does not freeze membership.

In-memory Skip may walk skipped elements, and remote providers may use different execution plans. Page arithmetic should be checked for negative inputs and overflow before it becomes part of a public request contract.

Request the first page and a page beyond the end. Decide whether the interface should show an empty page or clamp the index when the underlying collection becomes smaller.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var values = new[] { 9, 2, 7, 1, 5, 3, 8 };
var pageIndex = 1;
var pageSize = 3;
var page = values.OrderBy(x => x).Skip(pageIndex * pageSize).Take(pageSize);
Console.WriteLine(string.Join(",", page));

Expected output

5,7,8
Try this
Choose an explicit order before taking a page.