Paging Caml Queries in C# - Microsoft SharePoint Online

Dominic Jarvis, 18 May 2018

When working with SharePoint, there are times that you may need to execute a Caml Query to perform a more complex query than can be executed using out of the box methods. Using the C# SharePoint Client sdk, there is very little in the way of documentation for working with this functionality.

For the purposes of this example, I’ll show how to obtain a list of all items in a certain list by using a function called GetItems. This function can work without updating the default Caml Query definition, but will fail on large amounts of items due to the amount of data exceeding the limits of the query.

In these instances, you will need to implement some form of paging for the query. This has the following steps:

1. Create the Caml Query. This will contain the view XML that will define the query, and the ‘ListItemCollectionPosition’, which will describe where the query should take place from.
2. Limit the number of rows returned. This will prevent a single query from exceeding the record limit and crashing.
3. If desired, add a filter to the fields returned. Reducing the number of fields returned will increase the speed of the query.
4. Perform the query.
5. Update the ListItemCollectionPosition on the Caml query.
6. Repeat 4 & 5 until all records have been returned.

When this has been implemented in C#, this will look something like the following:

image

This query will retrieve all items in the list.

For completion, an alternative way of generating the query is:

image

Also, please note that in the above examples, the List< > object which the results are stored in is a List from System.Collections.Generic, not from the SharePoint namespace. The List object in the method definition is from the SharePoint namespace however (Microsoft.SharePoint.Client).