How to use CAML query with SharePoint 2013 List

iklan atas artikel
Hi There,

So its a very basic question that how would you use a CAML query to fetch items from a SharePoint list? Its very simple to use and very fast as compared to other list query options. Below is the stuff to understand.

I have a list that have Posts of my blog as its a blog site. I have to query below few columns using their internal names. 


To find internal name of the columns, you can use a tool "SP CAML Query Helper Online"  or try with any other method. This tool is very helpful in building CAML query. In below screenshot i am using internal name of "# Comments" which is  "NumComments".


The Code:
                  I am getting most recent three items from the list based on the created date and order by Created date descending. 

The columns you wan to select from the list should be in ViewFields.


private SPListItemCollection GetListItems(SPList oList)
{
string sQuery = @"<OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>";
string sViewFields = @"<FieldRef Name=""ID"" /><FieldRef Name=""LinkTitleNoMenu"" /><FieldRef Name=""Author"" /><FieldRef Name=""LikesCount"" /><FieldRef Name=""NumComments"" />";
string sViewAttrs = @"Scope=""Recursive""";
uint iRowLimit = 3;

var oQuery = new SPQuery();
oQuery.Query = sQuery;
oQuery.ViewFields = sViewFields;
oQuery.ViewAttributes = sViewAttrs;
oQuery.RowLimit = iRowLimit;
oQuery.ViewFieldsOnly = true;

SPListItemCollection collListItems = oList.GetItems(oQuery);

return collListItems;

}


This pass this method your list object and it will return the desired data.

Hope this will help someone to get idea.

Happy SharePointing...!
iklan atas artikel

You May Also Like

Subscribe by Email

How to use CAML query with SharePoint 2013 List
4/ 5
Oleh