Retrieving specific fields from a specified number of items using CSOM in SharePoint

In this article I will show you to Retrieving specific fields from a specified number of items using CSOM in SharePoint. If you need to retrieve only top 5 item from a list without caml query, using below example can achieve it.

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";
                foreach (char c in Passwords.ToCharArray()) passWord2.AppendChar(c);
                clientCont.Credentials = new SharePointOnlineCredentials(UserName, passWord2);
                List oList = clientCont.Web.Lists.GetByTitle("Country");

                CamlQuery camlQuery = new CamlQuery();
                ListItemCollection collListItem = oList.GetItems(camlQuery);

                clientCont.Load(
                    collListItem,
                    items => items.Take(5).Include(
                    item => item["Title"],
                    item => item["City_x0020_Name"]
                    ));

                clientCont.ExecuteQuery();

                foreach (ListItem oListItem in collListItem)
                {
                    Console.WriteLine("Title: {0},City Name: {1} ", oListItem["Title"], oListItem["City_x0020_Name"]);
                }
                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.