Sharepoint - How do I query a list using CAML and SPQuery?

The MSDN documentation for the SPQuery class has a code example of using SPQuery to interrogate a list.

Here is the code sample in case it changes over time:

using (SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb)
{

    SPList oList = oWebsiteRoot.Lists["Tasks"];

    SPQuery oQuery = new SPQuery();
    oQuery.Query = "<Where><Eq><FieldRef Name='Status'/>" +
        "<Value Type='Text'>Completed</Value></Eq></Where>";
    SPListItemCollection collListItems = oList.GetItems(oQuery);

    foreach (SPListItem oListItem in collListItems)
    {
        Response.Write(SPEncode.HtmlEncode(oListItem["Title"].ToString()) + 
            "<BR>");
    }
}

The logic inside the foreach is where you will perform whatever task you need to do on that particular item. You access the fields using the indexer inside the brackets, so in this example you can see the Title of the List Item is accessed.

Tags:

Object Model