1

I've got a .NET application that needs to retrieve items from a list and return them, I'm looking for a way to paginate the results in case the number of items gets too large.

I've checked out multiple questions about it, most are from 2013 saying the only way is to compare the last ID retrieved, but I also see that there's a REST skiptoken property that works in a similar way, but can't find a CAML equivalent.

Is my only solution just doing something like this?

<Where>
    <And>
        <Eq>
            <FieldRef Name='_ModerationStatus' /> <Value Type="ModStat">0</Value>
        </Eq>
        <Gt>
            <FieldRef Name='ID' /> <Value Type="Number">{lastId}</Value>
        </Gt>
    </And>
</Where>
<RowLimit>10</RowLimit>
1
0

SPQuery has a ListItemCollectionPosition property that is used for pagination. Using it is a best practice for getting large numbe of list items without blocking the content database.

Helper Method that gets all items in a large SharePoint list

private static void GetAllItems(SPList list, int itemCount, SPQuery query, string lastItemIdOnPage, List<SPListItem> listItems)
{
    while (true)
    {
        query.ViewFieldsOnly = true;
        query.RowLimit = (uint)itemCount;
        if (lastItemIdOnPage != null)
        {
            SPListItemCollectionPosition pos = new SPListItemCollectionPosition(lastItemIdOnPage);
            query.ListItemCollectionPosition = pos;
        }

        SPListItemCollection spListItems = list.GetItems(query);
        if (spListItems == null)
        {
            itemCount = 0;
        }
        else
        {
            if (spListItems.ListItemCollectionPosition == null)
            {
                listItems.AddRange(spListItems.Cast<SPListItem>());
                break;
            }

            lastItemIdOnPage = spListItems.ListItemCollectionPosition.PagingInfo;
            itemCount = spListItems.Count;
            listItems.AddRange(spListItems.Cast<SPListItem>());
        }
    }
}

Usage

List<SPListItem> listItems = new List<SPListItem>();
SPQuery query = new SPQuery();
query.Query = @"
                <Where>
                    <And>
                        <Eq>
                            <FieldRef Name='_ModerationStatus' /> <Value Type='ModStat'>0</Value>
                        </Eq>
                        <Gt>
                            <FieldRef Name='ID' /> <Value Type='Number'>{lastId}</Value>
                        </Gt>
                    </And>
                </Where>
                <RowLimit>10</RowLimit>";

int itemCount = 500;

GetAllItems(list, itemCount, query, null, listItems);
return listItems;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.