Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharePoint : Check if item exists in a list, minimum overhead

Tags:

sharepoint

How can I check if a list contains an item... really only interested in checking 1 field, not every single field in the list.

How can this be done in the most efficient way, creating a SPListItemCollection and itterating through this to check for unique values is really going to flatline the cpu usage... Surely there must be a way to do this without itterating through every item in the list?

like image 457
JL. Avatar asked Aug 27 '09 11:08

JL.


1 Answers

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.

like image 197
Alex Angas Avatar answered Oct 22 '22 13:10

Alex Angas