Retrieving SharePoint List items using list item collection position CSOM

In this article you will learn to Retrieving SharePoint List items using list item collection position CSOM. Using the ListItemCollectionPosition class you can implement paging SharePoint list item retrieval according to the position of SP items relative to their collection. RowLimit element can specify total number of items return per page.

 

using Microsoft.SharePoint.Client;
using System;
using System.Security;
using System.Linq;

namespace TokenAuthentication
{
    class Program
    {
       static string Passwords = "Password";
       static string UserName = "UserName";
       static string SiteURL = "Site URL";
        static void Main(string[] args)
        {

            using (ClientContext clientCont = new ClientContext(SiteURL))//PWA Url
            {
                SecureString passWord2 = new SecureString();
                foreach (char c in Passwords.ToCharArray()) passWord2.AppendChar(c);
                clientCont.Credentials = new SharePointOnlineCredentials(UserName, passWord2);
                List oList = clientCont.Web.Lists.GetByTitle("City");

                ListItemCollectionPosition itemPosition = null;

                while (true)
                {
                    CamlQuery camlQuery = new CamlQuery();

                    camlQuery.ListItemCollectionPosition = itemPosition;

                    camlQuery.ViewXml = "<View><ViewFields><FieldRef Name='ID'/>" +
                        "<FieldRef Name='Country_x0020__x0020_Name'/><FieldRef Name='City_x0020_Name'/>" +
                        "</ViewFields><RowLimit>2</RowLimit></View>";

                    ListItemCollection collListItem = oList.GetItems(camlQuery);

                    clientCont.Load(collListItem);

                    clientCont.ExecuteQuery();

                    itemPosition = collListItem.ListItemCollectionPosition;

                    foreach (ListItem oListItem in collListItem)
                    {
                        Console.WriteLine("Country Name: {0}: City Name: {1}", oListItem["Country_x0020__x0020_Name"], oListItem["City_x0020_Name"]);
                    }

                    if (itemPosition == null)
                    {
                        break;
                    }

                    Console.WriteLine("\n" + itemPosition.PagingInfo + "\n");
                }
                Console.ReadLine();
            }
        }
    }
}


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.