How to implement pagination and maxItemCount with Cosmos DB feediterator

Agnete Røstad 1 Reputation point

I'm trying to write Read method where maxItemCount continuation token is passed as arguments, but I'm not able to find any updated guides on how to implement it. The code I have now looks like this, but I can't believe there's no easier way to implement this basic functionality?

public async Task<(IEnumerable<T> Results, string ContinuationToken)> ReadAsync(Expression<Func<T, bool>> predicate, int limit, string continuationToken)
            var entityList = new List<T>();
            int itemsRemaining = limit;

                var maxItemsCount = Math.Min(itemsRemaining, 100);
                var options = new QueryRequestOptions { MaxItemCount = maxItemsCount };
                var query = _container.GetItemLinqQueryable<T>(true, continuationToken, options).Where(predicate);

                using (var iterator = query.ToFeedIterator())
                    if (iterator.HasMoreResults)
                        FeedResponse<T> response = await iterator.ReadNextAsync();
                        continuationToken = response.ContinuationToken;

                        if (iterator.ReadNextAsync().Result.Count == 0)
                            continuationToken = null;
                itemsRemaining -= maxItemsCount;
            while (itemsRemaining > 0);

            return (entityList, continuationToken);
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
974 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Navtej Singh Saini 4,171 Reputation points

    anonymous user

    Please check this example from Stack Overflow. If this doesn't help, please get back to us and we will try to help further.

    Navtej S