Rubén
Rubén

Reputation: 29

.NET Graph SDK Count Sharepoint Online List Items

I'm trying to get a count of list items in a Sharepoint Online list but Graph throw an exception with the following message "invalidRequest - $count is not supported on this API. Only URLs returned by the API can be used to page."

It's not possible to do this operation with a sharepoint list?

public async Task<int> GetListItemsCountAsync(string siteId, string listId, List<QueryOption> queryOptions)     
{
    queryOptions ??= new List<QueryOption>();

    var countQueryOption = new QueryOption("count", "true");
    queryOptions.Add(countQueryOption);

    var listItems = await _graphService.Client
        .Sites[siteId]
        .Lists[listId]
        .Items
        .Request(queryOptions)
        .GetAsync();

    return (listItems?.Count ?? 0);
}

Another option could be to get all the elements of the list and use the Count property of the resulting collection. But the performance of this approach seems worse.

Upvotes: 0

Views: 461

Answers (1)

user2250152
user2250152

Reputation: 20778

At least $count and $filter (for some properties like id) operator doesn't work for GET https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items.

As an alternative, you can select only id property to be returned. It will reduce the size of the response. Then use count on the resulting collection.

public async Task<int> GetListItemsCountAsync(string siteId, string listId, List<QueryOption> queryOptions)     
{
    queryOptions ??= new List<QueryOption>();

    var listItems = await _graphService.Client
        .Sites[siteId]
        .Lists[listId]
        .Items
        .Request(queryOptions)
        .Select("id")
        .GetAsync();

    return (listItems?.Count ?? 0);
}

Upvotes: 1

Related Questions