Question

I have a SPList but I don't need to go through everything in that list. I need to establish a CAML query so I can limit the list items. Then, go thru each item from the query result and do something. How do I use the object model to query a list with the following CAML query?

<Where>
  <Eq>
    <FieldRef Name='Active' />
    <Value Type='Boolean'>true</Value>
  </Eq>
</Where>
Was it helpful?

Solution

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.

OTHER TIPS

Here's a Linq way. I'm demonstrating the return of a single item:

SPList nums = web.Lists.TryGetList("Some List");
var filtered = nums.Items.Cast<SPListItem>().FirstOrDefault(k => k["Content Type Name"].ToString().Equals(key));
if (filtered != null)
{
   //do whatever you want to the returned item(s)
   filtered["Some Field"] = MyValue;
   filtered.Update();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top