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

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?

share|improve this question

2 Answers 2

up vote 12 down vote accepted

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];
share|improve this answer
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

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

share|improve this answer

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.