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?

    <FieldRef Name='Active' />
    <Value Type='Boolean'>true</Value>
  • I've cleaned up the comments, edited the information into @luA's question, and reopened. @luA, I've also removed the answer you posted in the question; please post answers below.
    – Kit Menke
    Jun 28, 2011 at 22:06

2 Answers 2


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()) + 

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.

  • Thank you James. Now I dont have iterate through all the records. save me some time.
    – lu A
    Jun 29, 2011 at 4:52
  • ...and performance. By the way, if you are just starting writing custom sharepoint solutions i would suggest using camlex as it would allow you to generate CAML waay easyer. Jun 29, 2011 at 6:16
  • I was gonna suggest U2U (as everyone does), but that Camlex actually looks very interesting!
    – James Love
    Jun 29, 2011 at 7:15

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.