Get Top 5 list Items from Sharepoint List using CAML

This is a sample code for retrieving top 5 items from the SharePoint List.

SPQuery is the SharePoint class to initialize the CAML query.

This following Query will display the top 5 items OrderBy ID as Ascending is false.

using (SPSite objSite = new SPSite("<Site URL>"))

{

    using (SPWeb objWeb = objSite.OpenWeb())

   {

      SPList spList = objWeb.GetList("<List URL>");

      SPQuery spQuery = new SPQuery();

      spQuery.Query = "<Query>

      <OrderBy>

     <FieldRef Name='ID' Ascending='False' />

     </OrderBy> </Query> ";

     spQuery.RowLimit = 5;

     SPListItemCollection spListItemCollection = spList.GetItems(spQuery);

  }

}

Ebook Download
View all
Learn
View all