SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>
share|improve this question
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 '11 at 22:06
up vote 7 down vote accepted

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.

share|improve this answer
Thank you James. Now I dont have iterate through all the records. save me some time. – lu A Jun 29 '11 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. – Janis Veinbergs Jun 29 '11 at 6:16
I was gonna suggest U2U (as everyone does), but that Camlex actually looks very interesting! – James Love Jun 29 '11 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;
share|improve this answer
Don't use SPList.Items directly, it's slow and gets slower very fast as the list grows in size. Reference:… – James Love May 26 '15 at 14:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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