10

Currently I am using a foreach loop to find the item I want by its title using the following code:

                SPList list = web.Lists.TryGetList("DocumentLibrary");
                foreach (SPListItem item in list.Items)
                {
                    if (item.Title == "Title")
                        return true;
                }

Is there a faster way to do this? Perhaps a CAML query?

15

You can also use SPQuery and a CAML query, like below. I also agree with what Dave Wise said about PortalSiteMapProvider class.

SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">YourTitle</Value></Eq></Where>";
query.RowLimit = 1;
query.ViewFields = "";
SPListItemCollection items = list.GetItems(query);
SPListItem item = items[0];
  • 3
    It should also be noted the PortalSiteMapProvider class only improves performance if the data is changed infrequently. Here's an excerpt from the article provided by @Dave Wise: "Also, using the above methods to fetch data which frequently changes can also be counterproductive. If the data changes frequently, it will be frequently invalidated and re-fetched from that database negating the benefits of caching. The invalidation mechanism is relatively coarse, with a change to a particular item invalidating any data in the same web as the item." – iOnline247 Mar 14 '12 at 19:00
  • 1
    Take care in the query it's </Eq> before </Where>. They're a mistake here. query.Query = "<Where>" + "<Eq>" + "<FieldRef Name=\"Title\"/>" + "<Value Type=\"Text\">YourTitle</Value>" + "</Eq>" + "</Where>"; query.ViewFields = ""; – user16099 Apr 4 '13 at 10:21
6

The PortalSiteMapProvider is the fastest way to access content and you should be able to do what you need with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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