How to: Submit a Query to a List

The following procedure demonstrates how to use the CAMLQueryBuilder class to submit a query to a list.

To submit a query to a list

  1. In Visual Studio, add a reference to the SharePoint Guidance Library Microsoft.Practices.SPG.Common.dll. If you are writing a feature receiver, item event receiver, workflow or anything else that needs to be in the global assembly cache, the Microsoft.Practices.SPG.Common assembly also needs to be in the global assembly cache.
  2. Define the query that your repository will provide.
  3. Open the SPSite and SPWeb objects that contain the list. Remember to properly dispose of these objects when you finish.
  4. Use an instance of the CAMLQueryBuilder class to create an SPQuery object. Pass the SPQuery object to the list's GetItems method.

The following code shows an example of the preceding steps.

public IList<Customer> GetAllCustomers()
{
  // ...
         
  using (SPSite site = new SPSite(customerWebUrl))
  {
      using (SPWeb customerWeb = site.OpenWeb())
      {
         SPList customerList = 
                customerWeb.Lists[Constants.CustomerListName];
         CAMLQueryBuilder camlQueryBuilder = new CAMLQueryBuilder();
         camlQueryBuilder.FilterByContentType(CustomerContentTypeName);
         SPListItemCollection items =  
                    customerList.GetItems(camlQueryBuilder.Build());

         // ...

      }
  }
}

Home page on MSDN | Community site