Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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>
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
add comment

1 Answer

up vote 5 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()) + 
            "<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.

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
add comment

Your Answer

 
discard

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.