Xpandables.AsyncPaged 11.0.0

dotnet add package Xpandables.AsyncPaged --version 11.0.0
                    
NuGet\Install-Package Xpandables.AsyncPaged -Version 11.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Xpandables.AsyncPaged" Version="11.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xpandables.AsyncPaged" Version="11.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Xpandables.AsyncPaged" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Xpandables.AsyncPaged --version 11.0.0
                    
#r "nuget: Xpandables.AsyncPaged, 11.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Xpandables.AsyncPaged@11.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Xpandables.AsyncPaged&version=11.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Xpandables.AsyncPaged&version=11.0.0
                    
Install as a Cake Tool

๐Ÿ“ฆ System.AsyncPaged

License .NET Version NuGet Version NuGet Downloads

Asynchronous paginated enumeration with offset-based and cursor-based pagination, BCL-aligned LINQ operators, and JSON streaming

Overview โ€ข Getting Started โ€ข Core Types โ€ข Creating Sequences โ€ข Strategies โ€ข LINQ โ€ข JSON โ€ข Tokens โ€ข Cursor โ€ข IQueryable โ€ข Disposal โ€ข AOT


๐Ÿ“‹ Overview

Xpandables.AsyncPaged provides IAsyncPagedEnumerable<T>: an IAsyncEnumerable<T> that also carries its pagination (Pagination: page size, current page, total count, continuation token) and owns what it reads from (IAsyncDisposable). On top of it the package offers:

  • factories over an IAsyncEnumerable<T>, an IQueryable<T> (with Skip/Take extraction and an asynchronous count), or a deferred factory call;
  • three enumeration strategies that keep the pagination fixed or update it per page or per item;
  • a paged overload of every deferred System.Linq.AsyncEnumerable operator, plus windowing operators, so a sequence stays paged through a whole LINQ chain;
  • streaming JSON serialization to a PipeWriter/Stream and deserialization from a PipeReader/Stream/HttpContent as { "pagination": โ€ฆ, "items": [ โ€ฆ ] };
  • cursor (keyset) options with reflection-free token formatting and parsing.

Everything is Native AOT compatible: no reflection-based JSON, no runtime type conversion.


๐Ÿš€ Getting Started

dotnet add package Xpandables.AsyncPaged
using System.Collections.Generic;
using System.Linq;

IAsyncEnumerable<Order> source = GetOrdersAsync();

// Attach a known pagination to any async sequence
IAsyncPagedEnumerable<Order> paged = source.ToAsyncPagedEnumerable(
    Pagination.Create(pageSize: 20, currentPage: 1, totalCount: 135));

Pagination pagination = await paged.GetPaginationAsync();
Console.WriteLine($"Page {pagination.CurrentPage}/{pagination.TotalPages} ({pagination.TotalCount} items)");

await foreach (Order order in paged)
{
    // โ€ฆ
}

await paged.DisposeAsync(); // releases what the sequence reads from

๐Ÿงฉ Core Types

IAsyncPagedEnumerable<T>

Member Description
GetAsyncEnumerator(ct) Returns an IAsyncPagedEnumerator<T> (also usable through await foreach).
GetPaginationAsync(ct) Returns the sequence's Pagination, computing it on first request.
WithStrategy(strategy) Returns a view of the same sequence enumerated with another PaginationStrategy (AsyncPagedEnumerable<T> โ€” also operator results and the PipeReader JSON overloads โ€”, ordered sequences and a view of a deferred sequence return the same instance when the strategy is unchanged; the sequence Create(factory) or ReadFromJsonAsAsyncPagedEnumerable returns, and the Stream JSON overloads, always return a new view).
DisposeAsync() Releases what the sequence owns (an HTTP response, a PipeReader, a database reader, a wrapped source).

The interface derives from both IAsyncEnumerable<T> and IAsyncDisposable; paged.ConfigureAwait(false) binds to IAsyncPagedEnumerableExtensions.ConfigureAwait, which configures the enumeration, so await foreach (var item in paged.ConfigureAwait(false)) compiles. The disposal is configured through its interface: ((IAsyncDisposable)paged).ConfigureAwait(false).

paged.ArgumentType (an extension property) returns typeof(T) for the call site's T, for code that handles paged sequences without knowing T statically. Because the interface is covariant, a sequence of string seen as IAsyncPagedEnumerable<object> reports object.

IAsyncPagedEnumerator<T>

An IAsyncEnumerator<T> with:

  • ref readonly Pagination Pagination โ€” the enumerator's current pagination, updated as items are read according to the strategy (no allocation on access);
  • PaginationStrategy Strategy โ€” the strategy, fixed for the enumerator's lifetime.

AsyncPagedEnumerator.Create(sourceEnumerator, pagination, strategy, ct) wraps any IAsyncEnumerator<T>; AsyncPagedEnumerator.Empty<T>(pagination) returns an enumerator that yields nothing.

Pagination

A readonly record struct. Page numbers are 1-based; 0 means no page is selected.

Member Description
PageSize, CurrentPage Required, zero or greater (ArgumentOutOfRangeException otherwise).
TotalCount Required, null when unknown, zero or greater otherwise.
ContinuationToken Required, null or empty when there is none.
Pagination.Empty 0, 0, no token, unknown total.
Pagination.Create(pageSize, currentPage, continuationToken, totalCount) Validated factory.
Pagination.FromTotalCount(totalCount) A total only: PageSize and CurrentPage are 0.
Pagination.FromSkipTake(skip, take, totalCount) Page skip / take + 1 (at most int.MaxValue) of size take; without take (or with take 0) a single page holds every row. A negative or null total is unknown; a total above int.MaxValue is clamped. A negative skip or take throws ArgumentOutOfRangeException.
Pagination.FromRequest(pageSize, token, limits, protector) The page a client asked for, validated: a null size gets limits.DefaultPageSize, a size above limits.MaxPageSize is clamped to it, zero or less throws PageSizeOutOfRangeException (an ArgumentOutOfRangeException); the token is read with ContinuationToken.Parse (CursorTokenException). Returns a PageRequest: PageSize, Token, and GetOffset() (0 without a token; a cursor token has none).
NextPage(continuationToken) CurrentPage + 1 (at most int.MaxValue) with the new token.
PreviousPage() CurrentPage - 1 and no token, or the same value on the first page.
WithTotalCount(totalCount) Same pagination with another total.
Skip, Take (CurrentPage - 1) * PageSize (0 when no page or no size), and PageSize.
TotalPages ceil(TotalCount / PageSize), or null when the total is unknown or PageSize is 0.
IsFirstPage, IsLastPage, HasPreviousPage, HasNextPage Navigation flags; IsLastPage and HasNextPage are false when the total is unknown.
HasContinuation, IsUnknown, IsPaginated A token is present; the total is unknown; Skip > 0 || Take > 0.

PaginationLimits (MaxPageSize 1000 and DefaultPageSize 50 by default) is an options class; a handler validates its input once and pages with the result:

PageRequest page = Pagination.FromRequest(pageSize, continuationToken, limits);

IAsyncPagedEnumerable<Order> orders = query.Skip(page.GetOffset()).Take(page.PageSize).ToAsyncPagedEnumerable();

The computed members (Skip, TotalPages, IsLastPage, HasNextPage) compute in 64 bits, so they never overflow: Skip saturates at int.MaxValue for a page beyond it, and TotalPages of a total clamped to int.MaxValue is the exact page count.

PaginationJsonContext is the source-generated JsonSerializerContext of Pagination, for a Pagination serialized on its own: the four stored members in camelCase (the computed members are never serialized), every member written and required on read, names read case-insensitively. The paged JSON APIs below do not use it: they write and read the pagination value with the items' options.


๐Ÿญ Creating Paged Sequences

Entry point Pagination Default strategy
source.ToAsyncPagedEnumerable(pagination) The given value Manual
source.ToAsyncPagedEnumerable(totalCount) Pagination.FromTotalCount(totalCount); a negative total throws ArgumentOutOfRangeException Manual
source.ToAsyncPagedEnumerable(paginationFactory, strategy) The factory's result Manual
source.ToAsyncPagedEnumerable(strategy) Pagination.Empty: an unknown total, the source streamed (see below) Manual
AsyncPagedEnumerable.Create(source, paginationFactory?, strategy) The factory's result, or Pagination.Empty Manual
AsyncPagedEnumerable.Create(query, cursorOptions?, options?, strategy) / query.ToAsyncPagedEnumerable(strategy?, cursorOptions?) / query.ToAsyncPagedEnumerable(cursorOptions, options, strategy?) Derived from the query (IQueryable); counted synchronously only in memory Manual
AsyncPagedEnumerable.Create(query, totalCountAsync, cursorOptions?, options?, strategy) Derived from the query, counted asynchronously Manual
AsyncPagedEnumerable.Create(query, paginationFactory, strategy) / query.ToAsyncPagedEnumerable(paginationFactory, strategy) The factory's result Manual
AsyncPagedEnumerable.Create(factory) The pagination of the sequence the factory returns The strategy of the sequence the factory returns (see Deferred sequences)
AsyncPagedEnumerable.Empty<T>(pagination?) The given value, or Pagination.Empty Manual

Every entry point throws ArgumentNullException for a null source, query or factory.

How the pagination is computed

  • Lazily, once. The pagination factory (or the count) runs on the first GetPaginationAsync call. Its result is cached and shared by every view WithStrategy returns. A failed or cancelled attempt is not cached: the next caller runs it again.
  • Under the sequence's lifetime. The shared computation is cancelled when the sequence is disposed; each caller only observes its own token while waiting. An already computed pagination is returned even when the caller's token is cancelled. After disposal, GetPaginationAsync throws ObjectDisposedException.
  • Without a pagination factory, an IAsyncEnumerable<T> source is streamed: its pagination is Pagination.Empty (an unknown total), nothing is read to count it and nothing is buffered. The ItemAware strategy counts the items as they are read; MaterializeAsync reads them into memory when a count is needed up front.
  • The enumerator takes a snapshot. GetAsyncEnumerator copies the pagination computed so far (or Pagination.Empty when it is not computed yet); the enumerator does not observe a later computation. Call GetPaginationAsync (or PrecomputePaginationAsync) before enumerating when the enumerator's Pagination matters.

Deferred sequences

AsyncPagedEnumerable.Create(factory) returns an AsyncPagedFactoryEnumerable<T> that calls factory(ct) on first use โ€” the first enumeration or pagination request of the enumerable or of any view WithStrategy returns โ€” and again after a failed attempt, until one succeeds. Initialization is thread-safe and its result is shared by every view, so an HTTP body behind it is read once. A factory that returns null throws InvalidOperationException. Disposing any view disposes the shared sequence (a sequence produced while disposal ran is disposed at once, and the call throws ObjectDisposedException); a pagination request or enumeration after disposal throws ObjectDisposedException.

The enumerable Create returns enumerates the produced sequence with that sequence's own strategy; until its first MoveNextAsync an enumerator reports Manual (a view: the strategy it was given). To enumerate with another strategy, apply it to the sequence the factory returns, or call WithStrategy on the result: a view enumerates the shared sequence with the strategy it was given.

Materialization

System.Linq.MaterializationExtensions:

Method Result
paged.PrecomputePaginationAsync(ct) Computes and caches the pagination now; returns the same sequence.
paged.MaterializeAsync(ct) Reads every item into memory; pagination Pagination.FromTotalCount(itemCount).
paged.MaterializeAsync(pageSize, currentPage = 1, ct) Same, with Pagination.Create(pageSize, currentPage, totalCount: itemCount).
source.ToMaterializedAsyncPagedEnumerableAsync(ct) An IAsyncEnumerable<T> read into memory, FromTotalCount(itemCount).
source.ToMaterializedAsyncPagedEnumerableAsync(pageSize, currentPage = 1, ct) Same, with the given page.

The page-size overloads throw ArgumentOutOfRangeException when pageSize or currentPage is zero or negative. The materialized sequence can be enumerated any number of times. The source is enumerated, not disposed.


๐Ÿงฎ Pagination Strategies

Strategy Enumerator behaviour
Manual The pagination stays the snapshot taken when the enumerator was created.
PageAware After each item, CurrentPage becomes (itemIndex - 1) / PageSize + 1 (1 when PageSize is 0).
ItemAware After each item, CurrentPage becomes the item index (and PageSize becomes 1 when it was 0). At the end of the sequence an unknown TotalCount becomes the number of items read.

Counts past int.MaxValue saturate (CurrentPage) or stay unknown (TotalCount) instead of overflowing.

IAsyncPagedEnumerable<Order> byPage = paged.WithPageAwarePagination();   // WithStrategy(PaginationStrategy.PageAware)
IAsyncPagedEnumerable<Order> byItem = paged.WithItemAwarePagination();   // WithStrategy(PaginationStrategy.ItemAware)
IAsyncPagedEnumerable<Order> fixedOne = paged.WithManualPagination();    // WithStrategy(PaginationStrategy.Manual)

await using IAsyncPagedEnumerator<Order> enumerator = byItem.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync())
{
    Console.WriteLine($"item {enumerator.Pagination.CurrentPage}");
}

A view returned by WithStrategy shares its source, its computed pagination and its lifetime with the original. When the source is a single-pass IAsyncEnumerable<T>, enumerate only one of the views.


๐Ÿ”— LINQ Extensions

The library provides LINQ operators in the System.Linq namespace for IAsyncPagedEnumerable<T>.

Aligned with System.Linq.AsyncEnumerable

Every deferred operator of System.Linq.AsyncEnumerable (.NET 11) has a paged overload with the same signature โ€” names, parameter names, defaults, nullability โ€” with the receiver and the return type made paged, and the same behaviour: argument validation, ParamName, exceptions, enumeration order, laziness, null keys. 101 of them โ€” the .NET 11 FullJoin and tuple-returning Join, GroupJoin, LeftJoin and RightJoin included โ€” are generated from the BCL surface by Xpandables.Generators while this library builds (see Paged Operators in System.Generators' README); ThenBy/ThenByDescending are written by hand.

The paged operators are exactly the BCL ones: a comparer is passed (or left null) on the aligned overload, and an asynchronous predicate takes the cancellation token, (item, cancellationToken) => โ€ฆ.

using System.Linq;

IAsyncPagedEnumerable<Order> source = GetPagedOrders();

// Still IAsyncPagedEnumerable<T> at every step โ€” no suffix, no cast.
IAsyncPagedEnumerable<string> report = source
    .Where(o => o.Total > 100)
    .OrderByDescending(o => o.CreatedOn)
    .ThenBy(o => o.Total)
    .Select(o => $"{o.Id}: {o.Total}");

Pagination pagination = await report.GetPaginationAsync();

Why the paged overload is chosen. The paged classes live in System.Linq, like AsyncEnumerable, so one using System.Linq; brings both into the same candidate set. A paged overload is the BCL signature with a more derived receiver, so C# overload resolution prefers it โ€” no cast, no ambiguity. It is not chosen when you call AsyncEnumerable.Where(paged, โ€ฆ) statically, when the receiver's static type is IAsyncEnumerable<T>, or when a closer extension (your own namespace, a using static) wins first.

Category Operators
Filtering / projection Where, Select, SelectMany, Cast, OfType, Index
Partitioning Take (count and Range), Skip, TakeLast, SkipLast, TakeWhile, SkipWhile, Chunk
Ordering Order, OrderDescending, OrderBy, OrderByDescending, ThenBy, ThenByDescending (sync and async keys), Reverse, Shuffle
Set operations Distinct, DistinctBy, Union, UnionBy, Intersect, IntersectBy, Except, ExceptBy, Concat, Append, Prepend, DefaultIfEmpty, Zip
Joins Join, GroupJoin, LeftJoin, RightJoin
Grouping / aggregation GroupBy, CountBy, AggregateBy
Windowing (no BCL equivalent) Window, WindowedSum, WindowedAverage, WindowedMin, WindowedMax (optional IComparer<T>), Pairwise, Scan โ€” each with a cancellation-aware (item, cancellationToken) => ValueTask<โ€ฆ> form except Window and Scan(seed, func)
IAsyncPagedEnumerable<Customer> enriched = source
    .Select(async (Order o, CancellationToken ct) => await LoadCustomerAsync(o.CustomerId, ct));

IOrderedAsyncPagedEnumerable<Order> byCustomer = source
    .OrderBy(async (o, ct) => await LoadRegionAsync(o.CustomerId, ct))
    .ThenBy(o => o.CreatedOn);

Windowing operators

These have no AsyncEnumerable equivalent. Each validates its arguments when called (ArgumentNullException, ArgumentOutOfRangeException for a windowSize below 1) and runs when enumerated.

Operator Yields
Window(windowSize) Overlapping T[] windows; only full windows: n โˆ’ windowSize + 1 of them, none when the source is shorter.
WindowedSum(windowSize, selector) The sum of each window, for int, long and double selectors. int/long sums use checked arithmetic and throw OverflowException; the double sum slides (subtract the leaving value, add the entering one), so rounding errors accumulate over long sequences.
WindowedAverage(windowSize, selector) The sliding double sum divided by windowSize.
WindowedMin / WindowedMax(windowSize, selector, comparer?) The extremum of each window, in O(n) with a monotonic deque (a ring buffer of windowSize slots allocated once per enumeration). null comparer: Comparer<T>.Default, which orders null first. Among equal values, the most recent one is returned.
Pairwise() / Pairwise(selector) (Previous, Current) tuples or selector(previous, current): n โˆ’ 1 results.
Scan(seed, func) The seed, then each running accumulation: n + 1 values.
Scan(func) The first element as is, then each running accumulation: n values.

Ordering and ThenBy

OrderBy, OrderByDescending, Order and OrderDescending (sync or async keys) return IOrderedAsyncPagedEnumerable<T>, which is what makes ThenBy/ThenByDescending available. Ordering is the BCL's: stable, every key computed once per element โ€” including ThenBy's key, which runs for every element and not only to break ties. An ordering result uses PaginationStrategy.Manual; a strategy set on the ordered sequence (with WithStrategy or a With*Pagination method) is kept through ThenBy/ThenByDescending. Those methods are typed IAsyncPagedEnumerable<T>, so cast their result back to IOrderedAsyncPagedEnumerable<T> to call ThenBy on it. The enumerator of an ordered sequence starts from the pagination its GetPaginationAsync (or that of another view of the same chain, ThenBy or WithStrategy) has read, and from Pagination.Empty before that, as for the other sequences.

An async-key ThenBy/ThenByDescending on an IOrderedAsyncPagedEnumerable<T> implemented outside this library throws NotSupportedException unless that type also implements IOrderedAsyncEnumerable<T>; every ordered sequence this library returns does. IOrderedAsyncPagedEnumerable<T>.CreateOrderedEnumerable(keySelector, comparer, descending) is the primitive the synchronous ThenBy operators call.

Note: ordering, Reverse, Shuffle, GroupBy, CountBy, AggregateBy and RightJoin buffer the whole sequence before yielding; Take(Range) counted from the end keeps a bounded look-ahead.

Pagination through operators

Operators never recompute pagination; they report only what is still true of the items they yield:

Family Operators Pagination of the result
Projections (1:1, same order) Select, Cast, Index, Scan(func), GroupJoin The source's, unchanged: total and continuation token included.
Everything else Filtering (Where, OfType, Take, Skip, TakeWhile, SkipWhile, TakeLast, SkipLast, Distinct(By), Except(By), Intersect(By)), ordering, Reverse, Shuffle, Zip, Pairwise, Window/Windowed*, Concat, Union(By), Prepend, Append, SelectMany, Scan(seed, func), DefaultIfEmpty, Chunk, GroupBy, CountBy, AggregateBy, Join, LeftJoin, RightJoin The source's page size and current page; TotalCount and ContinuationToken are null: they described the source, not these items.

Skip and SkipLast with a count of 0 or less return the source itself, its pagination included. The ItemAware strategy counts the items an operator yields; MaterializeAsync reports Pagination.FromTotalCount(itemCount).

With two sequences (Concat, Union, Zip, joins) only the receiver's pagination is used. Results use PaginationStrategy.Manual, except Skip and SkipLast with a count of 0 or less (which return the source itself) and ThenBy, which keeps the strategy of the ordered sequence it refines. A result computes its pagination on its first GetPaginationAsync and caches it; its enumerator takes the same snapshot as any AsyncPagedEnumerable<T> (see How the pagination is computed).

As in the BCL, LeftJoin/RightJoin pass default for the unmatched side, so the result selector must accept a null (or default) element.

Operator results and disposal

Every operator result disposes its paged receiver when it is disposed, so disposing the end of a chain releases the root โ€” an HTTP response, a PipeReader, a database reader. Disposing a result several times is safe: an operator result releases its receiver once, and an ordered result forwards each call to its receiver, whose disposal is idempotent for every sequence this library returns. The other sequences of an operator (second, inner, โ€ฆ) are not disposed, as in the BCL. Consequently, two results built from one source share it:

var cheap = orders.Where(o => o.Total < 10);
var dear = orders.Where(o => o.Total > 1000);
await cheap.DisposeAsync();   // disposes `orders`: `dear` reads from a released source after this

Dispose the source (or the last result) once you are done with every branch.

Terminal operators return a value rather than a sequence, so there is no pagination to preserve and the BCL versions are used directly:

List<Order> list = await source.ToListAsync();
Order[] array = await source.ToArrayAsync();
var dict = await source.ToDictionaryAsync(o => o.Id);
var lookup = await source.ToLookupAsync(o => o.CustomerId);

๐Ÿ”„ JSON Serialization

Wire format

{
  "pagination": { "totalCount": 135, "pageSize": 20, "currentPage": 1, "continuationToken": null },
  "items": [ โ€ฆ ]
}

The pagination value is a fixed contract, {"totalCount":โ€ฆ,"pageSize":โ€ฆ,"currentPage":โ€ฆ,"continuationToken":โ€ฆ}, written and read without metadata:

  • the four members are always written, in camelCase, whatever the PropertyNamingPolicy and DefaultIgnoreCondition of the items' options (totalCount and continuationToken are null when absent, the zeros are written); the items follow those options. The token's string value is encoded with the options' Encoder;
  • reading matches the names in any casing, skips other members (such as the computed properties of a body written elsewhere), and reads a missing member as its default: a null total or token, a zero page size or page; a null pagination is Pagination.Empty. A member of the wrong type, or a count beyond 32 bits, is a JsonException; a negative count, a JsonException.

Writing (System.Text.Json.JsonSerializerExtensions)

using System.Text.Json;

await JsonSerializer.SerializeAsyncPaged(pipeWriter, paged, AppJsonContext.Default.Order, ct);
await JsonSerializer.SerializeAsyncPaged(stream, paged, AppJsonContext.Default, ct);   // context overload

Overloads take a PipeWriter or a Stream, and a JsonTypeInfo<T> or a JsonSerializerContext (which throws InvalidOperationException when it does not register T).

  • The pagination is requested first (GetPaginationAsync), then the items are enumerated, so the enumerator starts from the computed pagination. The first item is read before anything is written: a failure computing the pagination or reading the first item leaves the output untouched.
  • The writer uses the WriteIndented and Encoder of the item metadata's options.
  • The output is flushed each time 16 KB are pending, and before waiting for an item the source has not produced yet (a database still reading, for example), as System.Text.Json does for an IAsyncEnumerable<T>: a reader sees items as they are produced, and a source that answers at once is written in large chunks. A source that waits before most items (a channel, a feed) is flushed item by item, and one that waits after its first item starts the output there.
  • When the reader on the other end of the pipe completes or cancels it, the next flush detects it and the serialization stops there, successfully: the remaining items and closing tokens are not written. A move the source had already started is awaited first (an enumerator is never disposed while it runs), so a source that ignores the cancellation token holds the serialization until it produces its next item.
  • The cancellation token is checked before each item. The enumerator is disposed on every path; the sequence itself is not (dispose it yourself).
  • The Stream overload leaves the stream open and completes its own PipeWriter on every path.

Reading (System.Text.Json.JsonDeserializerExtensions)

// Returns at once; the input is read as the sequence is enumerated or its pagination requested.
IAsyncPagedEnumerable<Order?> orders = JsonSerializer.DeserializeAsyncPagedEnumerable(
    stream, AppJsonContext.Default.Order, PaginationStrategy.Manual,
    // readerOptions: new PagedJsonReaderOptions { MaxHeaderBytes = 64 * 1024 } bounds the header
    cancellationToken: ct);

// A root JSON array (no pagination object)
IAsyncPagedEnumerable<Order?> fromArray = JsonSerializer.DeserializeAsyncPagedEnumerable(
    pipeReader, topLevelValues: true, AppJsonContext.Default.Order);
  • Ownership. The Stream overloads own the stream; the enumeration that reads the items closes it when it ends (at the end of the items, on a failure, or when its enumerator is disposed early), or the sequence's disposal does, whichever comes first, once a read of the header in progress has ended. An enumerator that reads nothing (a second one, or one disposed before its first MoveNextAsync) closes nothing. A failure closing the stream is reported by the call that closes it: the last MoveNextAsync, or the disposal. The PipeReader overloads borrow the reader (for example HttpContext.Request.BodyReader): the caller completes it.
  • Format. The body is the wire format above: pagination is optional and comes before items; items comes last. Other root properties before items are skipped, whatever their value; pagination and items are matched in any casing (an escaped name too). With topLevelValues: true, a root array is read as the items (pagination Pagination.Empty). A UTF-8 byte order mark is skipped. The header โ€” everything before the opening bracket of items, or the whole body without items โ€” is read once, under the sequence's creation token, by whichever consumer asks first, so requesting the pagination never consumes the items; it is counted from the start of the body (a UTF-8 byte order mark excluded) to the start of the items array, and is at most PagedJsonReaderOptions.MaxHeaderBytes long (1 MiB by default); a longer one is a JsonException raised once that many bytes are read. The items array is then read by JsonSerializer.DeserializeAsyncEnumerable, in one pass, with the options of the item metadata. The header and the closing brace allow no comments.
  • Single pass. The items can be enumerated once (the input is a stream): a second enumeration throws InvalidOperationException (MaterializeAsync reads them into memory first), unless it reports the kept failure of the first. A pagination request after the items have been read returns the pagination of the header. A body without pagination reports Pagination.Empty.
  • Empty body. An empty (or blank) body is an empty page: no items, Pagination.Empty.
  • Errors are JsonExceptions. A body that is not in this format (two pagination members, an items value that is not an array, a comment in the header), a root array without topLevelValues: true, a scalar root, a pagination member of the wrong type or a negative count, or content after a body without items is reported by GetPaginationAsync and by the enumeration. Truncated or malformed JSON in the items, or content after the items array (a pagination placed after the items included), is reported by the enumeration; the header of such a body has no pagination, so GetPaginationAsync returns Pagination.Empty. A failure of the items is kept and reported to every later enumeration, never turned into an empty page; the pagination read before it stays available. A cancellation of the enumeration while it waits for the header leaves the items to the next enumeration; once the items are being read, it is kept like a failure. An exception other than a JsonException raised while a value is deserialized (for example one thrown by an item's own constructor or setter) is kept and reported the same way.
  • The cancellationToken passed at creation is observed by the enumeration together with the enumeration's own token; GetPaginationAsync observes its own token only.

Reading an HttpContent (System.Net.Http.Json.HttpContentExtensions)

using System.Net.Http.Json;

HttpResponseMessage response = await httpClient.GetAsync("api/orders", HttpCompletionOption.ResponseHeadersRead);
await using IAsyncPagedEnumerable<Order?> orders =
    response.Content.ReadFromJsonAsAsyncPagedEnumerable(AppJsonContext.Default.Order);

Pagination pagination = await orders.GetPaginationAsync();
await foreach (Order? order in orders) { /* โ€ฆ */ }

ReadFromJsonAsAsyncPagedEnumerable(jsonTypeInfo | context, strategy, readerOptions, ct) returns a deferred sequence: the content stream is opened on first use and shared by every WithStrategy view (pagination from one view, the items from another), and the items can be enumerated once across them. A non-UTF-8 charset in Content-Type is transcoded to UTF-8; an unknown charset throws InvalidOperationException on first use (the first pagination request or enumeration), not when the method is called. Disposing the sequence (or any view) releases the response body.

The content stream is opened with the token of the call that first uses the sequence; the items are read under the method's own cancellationToken, the sequence's token for its whole life, and the enumeration's token. A token passed to an earlier GetPaginationAsync(token) and cancelled later does not cancel the enumeration. GetPaginationAsync observes its own token only.

Reading a response in either form (System.Net.Http.Json.HttpResponseMessageExtensions)

A server running Xpandables.AspNetCore.AsyncPaged answers a client that asks for JSON Lines (Accept: application/jsonl) with the items one per line and the pagination in headers (System.Text.Json.PagedJsonLines). Read the response, not its content, to get both forms:

using HttpRequestMessage request = new(HttpMethod.Get, "api/orders");
request.Headers.Accept.ParseAdd(PagedJsonLines.MediaType);
using HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

await using IAsyncPagedEnumerable<Order?> orders = response.ReadFromJsonAsAsyncPagedEnumerable(AppJsonContext.Default.Order);
Pagination pagination = await orders.GetPaginationAsync(); // X-Total-Count, X-Page-Size, X-Current-Page, Link
  • JSON Lines (application/jsonl or application/x-ndjson) is read with .NET 11 JsonSerializer.DeserializeAsyncEnumerable(โ€ฆ, topLevelValues: true); its pagination is read from the headers by PagedJsonLines.ReadPagination (Pagination.Empty when they carry none; a malformed value is left unknown). Any other content type is the paged JSON body, read as above.
  • The building blocks are public: JsonSerializer.DeserializeAsyncPagedLines(stream, jsonTypeInfo, pagination), HttpContent.ReadFromJsonLinesAsAsyncPagedEnumerable and HttpContent.ReadFromJsonLinesAsAsyncEnumerable. The items of a JSON Lines stream can be enumerated once; the sequence owns the stream.

๐ŸŽซ Continuation Tokens

A continuation token is opaque: base64url, without padding, of version | kind | payload. ContinuationToken writes and reads it.

Member Description
ContinuationToken.ForOffset(offset) The offset of the next page (zero or greater).
ContinuationToken.ForCursor(key, tieBreaker) The key of the last row read and its tie-breaker (null for a unique key), as invariant strings.
Format(protector) The token's text; with an ICursorTokenProtector, the text of the protected bytes.
ContinuationToken.Parse(text, protector) Reads what Format writes; throws CursorTokenException (a FormatException) otherwise.
Kind, Offset, Key, TieBreaker The position the token resumes from.

Format throws InvalidOperationException when its text would exceed ContinuationToken.MaxLength (4096 characters), which Parse would refuse: a cursor token holds at most 3,067 UTF-8 bytes of key and tie-breaker unsigned (one or two fewer with a tie-breaker, for its length prefix), 3,035 with HmacCursorTokenProtector, and less with the overhead of Data Protection. ForCursor throws ArgumentException for a key or tie-breaker with a lone surrogate.

Parse refuses a token that is empty, longer than ContinuationToken.MaxLength characters, not base64url, of another version or an unknown kind (ContinuationTokenKind.None is never written), truncated, a varint not in its shortest form, followed by other bytes, or whose signature does not verify.

ICursorTokenProtector (Protect/Unprotect over the token's bytes) authenticates a token, so a client cannot present a position the server did not issue. Tokens are unsigned by default. HmacCursorTokenProtector(key) appends a 32-byte HMAC-SHA256 of the token (the key has at least 32 bytes) and verifies it in constant time; Xpandables.AspNetCore.AsyncPaged registers a protector over ASP.NET Core Data Protection.

var protector = new HmacCursorTokenProtector(signingKey);

string token = ContinuationToken.ForOffset(40).Format(protector);
ContinuationToken read = ContinuationToken.Parse(token, protector); // read.Offset == 40

๐ŸŽฏ Cursor Pagination

A keyset cursor pages a query by the value of a key instead of an offset: each page starts after the last row of the previous one, so rows inserted or deleted elsewhere never shift a page, and the database seeks with an index instead of skipping rows. CursorOptions<TSource> describes it: the key (KeySelector, CursorType), the tie-breaker that orders rows sharing a key (TieBreakerSelector, required unless the key is declared unique), the Direction (Forward: ascending, greater-than; Backward: descending, less-than), whether the row at the applied position starts the page (IsInclusive), and that position (AppliedToken).

static readonly CursorOptions<Order> ByDate = CursorOptions.For<Order>()
    .WithKey(o => o.CreatedOn, o => o.CreatedOn)   // an expression for the provider, the same selector as a delegate
    .ThenBy(o => o.Id, o => o.Id)                  // rows with the same CreatedOn: ordered by the unique Id
    .Backward()                                    // newest first
    .Build();

// A unique key needs no tie-breaker:
static readonly CursorOptions<Order> ById = CursorOptions.Create<Order, int>(o => o.Id, o => o.Id);
// or CursorOptions.For<Order>().WithKey(o => o.Id, o => o.Id).Unique().Build()

Each selector is given twice: as an expression, which a query provider translates, and as a delegate, with which the library reads the key of the last row and pages an in-memory query. Nothing is compiled. Build() throws InvalidOperationException for a key without tie-breaker that is not declared Unique(), and NotSupportedException for a nullable key or a type outside the supported set (bool and char, for instance, have no order a query can compare). A reference-type key or tie-breaker (a string) must be non-null on every row: FormatToken throws InvalidOperationException for a null one. WithFormatter/WithParser change how a supported key is written in the token; a parser rejects a string by throwing FormatException, OverflowException or ArgumentException (read as a CursorTokenException).

Paging. Pass the options to an IQueryable<T> entry point, with a query that ends with Take(pageSize) and has no Skip (else InvalidOperationException when the sequence is created):

using Microsoft.EntityFrameworkCore; // Xpandables.EntityFramework: counts with LongCountAsync

PageRequest request = Pagination.FromRequest(pageSize, continuationToken, limits, protector);
CursorOptions<Order> cursor = ByDate.WithAppliedToken(request.Token);   // CursorTokenException for a foreign token

IAsyncPagedEnumerable<Order> page = dbContext.Orders
    .Where(o => o.Status == "Active")
    .Take(request.PageSize)
    .ToAsyncPagedEnumerable(cursor, new PaginationOptions { Protector = protector });

The page is the rows after the applied position โ€” key > a, or (key > a) OR (key = a AND tieBreaker > b) with a tie-breaker; < backward; the last comparison >=/<= when inclusive โ€” ordered by the key then the tie-breaker, pageSize + 1 of them read in one query. The extra row proves a next page and is not yielded. The pagination:

Pagination Keyset page
PageSize The Take count.
CurrentPage 0: a keyset page has no number.
TotalCount The count of the query without its Take and without the cursor (Counting), or null with SkipTotal.
ContinuationToken When a next page exists, cursor.FormatToken(row, protector) of the last row yielded, or, for an inclusive cursor, of the extra row (the next page starts at it); otherwise null.

The rows are read once, with the pagination, and yielded from that read (a page holds at most pageSize rows). For a query provider the filter and the order are expressions built from the selectors' bodies; the applied values are members of a constant, which a provider sends as parameters. A string key is compared with string.Compare (the database's collation), an enum key as its underlying type. An in-memory query is filtered and ordered with the delegates (strings ordinally).

Tokens. cursor.FormatToken(row, protector) writes ContinuationToken.ForCursor(key, tieBreaker); cursor.ParseToken(text, protector) reads one back and checks its shape (a cursor token, the same tie-breaker presence, a key and tie-breaker that parse; a same-shaped token of another cursor is not detected, so sign each cursor's tokens with its own protector key to bind them to it); cursor.WithAppliedToken(token) positions a copy of the options. The default conversion is reflection-free and culture-invariant: strings, the numeric types, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan and enums (by name). DateTime, DateTimeOffset and TimeOnly use the round-trip format "O" (every fraction of a second, a DateTime's kind, an offset).


๐Ÿ“š IQueryable Integration

query.ToAsyncPagedEnumerable(strategy?, cursorOptions?), query.ToAsyncPagedEnumerable(cursorOptions, options, strategy?) and AsyncPagedEnumerable.Create(query, โ€ฆ) read one page of a query. Without cursor options the page is the query's own Skip/Take (offset paging): the query is enumerated as written, or, with SkipTotal and a positive Take, read once with one extra row (Skip(skip).Take(take + 1), the extra row not yielded) together with its pagination. With cursor options it is a keyset page (Cursor).

Pagination Value
PageSize The Take count, or 0.
CurrentPage skip / take + 1 (at most int.MaxValue) with a Take; 0 without one, or when a Skip or Take count is not a constant (unknown: HasNextPage and IsLastPage then say nothing about the page).
TotalCount The count of the query without its Skip/Take (clamped to int.MaxValue; a negative count is unknown), or null with PaginationOptions.SkipTotal.
ContinuationToken ContinuationToken.ForOffset(skip + take) (a missing or negative Skip counts as 0), formatted with PaginationOptions.Protector, when Take is positive and a next page may exist; otherwise null. A counted total offers it when the offset is smaller than the total (so an empty page has none); a negative count, an unknown total, cannot rule the next page out and offers it on every page, an empty one included, so a chain over such a source ends only with SkipTotal (the extra row proves the next page) or a non-negative count. A page whose Skip or Take count is not a constant has no token: the query is enumerated as written.

Counting

The total is counted once, on the first pagination request (again after a failed attempt), with a token cancelled when the sequence is disposed:

  • an in-memory query (AsQueryable(), provider EnumerableQuery) is counted with LongCount();
  • any other provider is counted by the delegate of AsyncPagedEnumerable.Create(query, totalCountAsync, โ€ฆ), which receives the query without its page; the ToAsyncPagedEnumerable overloads of Xpandables.EntityFramework count with LongCountAsync, and query.ToAsyncPagedEnumerable(cursorOptions, options) among them counts that way unless SkipTotal is set; it takes no strategy, so apply one with .WithStrategy(strategy) on the result. Without a delegate, and without SkipTotal, the call throws InvalidOperationException when the sequence is created, rather than block a thread on the database;
  • PaginationOptions { SkipTotal = true } leaves the total unknown and runs no count.
PaginationOptions Default Effect
SkipTotal false No count; TotalCount is null.
Protector null Signs the continuation token, offset or cursor (ICursorTokenProtector).
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

IQueryable<Order> query = dbContext.Orders
    .Where(o => o.Status == "Active")
    .OrderBy(o => o.Id)
    .Skip(40)
    .Take(20);

IAsyncPagedEnumerable<Order> page = AsyncPagedEnumerable.Create(
    query,
    (countQuery, ct) => new ValueTask<long>(countQuery.LongCountAsync(ct)));

Pagination pagination = await page.GetPaginationAsync(); // PageSize 20, CurrentPage 3, TotalCount = all active orders

A pagination factory (AsyncPagedEnumerable.Create(query, paginationFactory, strategy)) replaces this derivation: nothing is counted, the query's Skip/Take are not read.

QueryPaginationNormalizer

The expression-tree helper behind the derivation, usable on its own. None of its methods executes the query.

Method Result
Normalize(query) (Queryable, Skip, Take): the query without Skip/Take and their counts, in one pass.
ExtractSkipTake(query) (Skip, Take) only.
RemoveSkipTake(query) The query without Skip/Take.

The page is the Queryable.Take(int) and Queryable.Skip(int) at the top of the query, Take(Skip(source)), Skip(source) or Take(source), seen through the operators that keep the rows above it (Select, Cast and a provider's own operators such as EF Core's AsNoTracking or Include). It is removed, including a count that is not a constant; a count is reported only when it is a constant. Any other Skip or Take belongs to the query the page applies to and is kept: one below a Where, an ordering or another page (q.Take(20).Skip(40) reports Skip 40 over the 20 rows Take(20) keeps), one inside a predicate (a subquery's Take(1)), a join's inner sequence or a Concat's second sequence. A page below a Where is no page: nothing is reported or removed. Take(Range), SkipLast, TakeLast, SkipWhile and TakeWhile are kept and not recognised.


๐Ÿงน Disposal and Thread Safety

  • AsyncPagedEnumerable<T> (returned by the Create overloads over a source or a query) cancels an in-flight pagination computation when disposed and releases its source once that computation has ended. DisposeAsync waits for it; Dispose does not (a release failure is thrown only when the release completes synchronously, and is otherwise visible to DisposeAsync callers). Every view returned by WithStrategy shares one disposal: a DisposeAsync on another view awaits the same release, and later calls are no-ops. Do not dispose the sequence from inside its own pagination factory: that waits on itself. After disposal GetPaginationAsync and GetAsyncEnumerator throw ObjectDisposedException.
  • AsyncPagedFactoryEnumerable<T> disposes the sequence its factory produced; Dispose starts that release without waiting for it.
  • Enumerators are disposed by await foreach; disposing one disposes the source enumerator, not the sequence.
  • Thread safety. The pagination computation, the deferred factory call and the JSON parser are safe to use from concurrent consumers; a single enumerator is not.

โšก Native AOT

Xpandables.AsyncPaged has no reflection path: every JSON API takes a JsonTypeInfo<T> or a JsonSerializerContext, the pagination value is written and read without metadata (PaginationJsonContext is source-generated), continuation tokens are binary and cursor keys are converted without reflection; a keyset cursor builds expressions for a query provider and pages an in-memory query with its delegates, compiling nothing, and the paged LINQ operators are generated by Xpandables.Generators when the library itself builds (nothing is generated in, or required from, your project). An IQueryable<T> source runs through the caller's own query provider: an in-memory AsQueryable() inherits that provider's trimming and Native AOT behavior, not the library's. Queryable.AsQueryable() is annotated [RequiresDynamicCode] and [RequiresUnreferencedCode] in .NET; the in-memory EnumerableQuery evaluates expression trees through the interpreter. A Native AOT application pages a real provider or an IAsyncEnumerable<T> source, or suppresses that warning at its own call site.


๐Ÿ“ฆ Package Contents

Namespace Types
System.Collections.Generic IAsyncPagedEnumerable<T>, IOrderedAsyncPagedEnumerable<T>, IAsyncPagedEnumerator<T>, AsyncPagedEnumerable / AsyncPagedEnumerable<T>, AsyncPagedFactoryEnumerable<T>, AsyncPagedEnumerator / AsyncPagedEnumerator<T>, Pagination, PaginationStrategy, PaginationJsonContext, CursorOptions / CursorOptions<T>, CursorOptionsBuilder<TSource>, CursorOptionsBuilder<TSource, TCursor>, CursorDirection, PaginationLimits, PageRequest, PaginationOptions, PageSizeOutOfRangeException, ContinuationToken, ContinuationTokenKind, CursorTokenException, ICursorTokenProtector, HmacCursorTokenProtector, QueryPaginationNormalizer, IAsyncEnumerableExtensions, IAsyncPagedEnumerableExtensions, IAsyncPagedEnumerableStrategyExtensions
System.Linq MaterializationExtensions, JoinExtensions, OuterJoinExtensions, GroupingExtensions, ProjectionExtensions, PaginationExtensions, OrderingExtensions, TransformationExtensions, SetExtensions, SetByExtensions, AggregationExtensions, WindowingExtensions
System.Text.Json JsonSerializerExtensions, JsonDeserializerExtensions, PagedJsonReaderOptions
System.Net.Http.Json HttpContentExtensions

๐Ÿ“„ License

Apache License 2.0 โ€” see the LICENSE file for details.


<div align="center">

Built with โค๏ธ using .NET 11

โฌ† back to top

</div>

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net11.0

    • No dependencies.

NuGet packages (8)

Showing the top 5 NuGet packages that depend on Xpandables.AsyncPaged:

Package Downloads
Xpandables.EntityFramework

Base implementation for Entity Framework integration. Does not support Native AOT: EF Core compiles queries at run time. Use Xpandables.Data for AOT or trimmed deployments.

Xpandables.Results

Result pattern implementation.

Xpandables.AsyncPaged.Json

IAsyncPagedEnumerable Json Serialization.

Xpandables.Rests

Declarative REST client: requests described by attributes and completed by source generation, composable request and response pipelines, resilience through Microsoft.Extensions.Http.Resilience; Native AOT compatible.

Xpandables.AsyncPaged.Linq

IAsyncPagedEnumerable linq.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.0.0 0 11/29/2026
10.0.2 311 3/15/2026
10.0.1 234 2/20/2026
10.0.0 223 1/9/2026