How to implement pagination and maxItemCount with Cosmos DB feediterator

Agnete Røstad 1 Reputation point
2021-04-21T07:38:24.71+00:00

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;

            do
            {
                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();
                        entityList.AddRange(response.Resource);
                        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.
919 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Navtej Singh Saini 4,171 Reputation points
    2021-04-23T23:46:39.347+00:00

    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.

    Regards
    Navtej S