Here's a good comparison of techniques from Waldek Mastykarz.
The general rule is to use SPQuery. See SharePointDevWiki for more details. Here's a basic example:
SPList list = SPContext.Current.Web.Lists["Some List"];
SPQuery query = new SPQuery();
query.Query = @"
<Where>
<Eq>
<FieldRef Name='SomeField' />
<Value Type='Text'>Value To Match</Value>
</Eq>
</Where>";
SPListItemCollection found = list.GetItems(query);
if (found.Count > 0)
{
// Do something
}
A few notes about SPQuery:
- If you get your query wrong, it can return all answers instead of giving an error
- If you get your query wrong, it can sometimes give an unhelpful/misleading error
- Make sure you get the Value Type correct
Save yourself a lot of trouble by using a tool such as U2U CAML Builder (Windows or Web versions - Web is better IMHO) or Stramit CAML Viewer to build and test your queries.