SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am going through all the lists in site collection, where list contains content type MvContentType, and for all list items in this list (this list only contain this content type, so all items have this content type), trying to get some fields/metadata values for all list items.

I dont need to get whole SPListItem but only some metadata for this item.

Is there any way to optimise this code or make it more efficient/better which are marked with "??" in code or whole code in general ?

        using (SPSite site = new SPSite(siteUrl))
            SPWebCollection spWebs = site.AllWebs;

            foreach (SPWeb web in spWebs)
                    SPListCollection lists = web.Lists; // ??
                    foreach (SPList list in lists)
                        SPContentType ctype = list.ContentTypes.Cast<SPContentType>().FirstOrDefault(ct => ct.Name.Contains("MyContentType"));
                        if (ctype != null)
                            int itemsCount = list.ItemCount - 1;
                            SPListItemCollection items = list.Items; // ??
                            for (int i = 0; i < itemsCount; i++)
                                SPListItem item = items[i]; // ??
                                String valueA = item["FieldA"]; // ??
                                String valueB = item["FieldB"]; // ??
                catch (Exception)
                    // some exception handling


share|improve this question
up vote 4 down vote accepted

Use SPSiteDataQuery which is created exactly for this.

It'll not optimize only the ?? parts but all of the traversing

If there is many items and you're using SharePoint server then you should use ContentIterator

share|improve this answer
thanks, it looks really useful. I expect to get total results to be more than 1 million, I guess it won't be a problem. – newcoderintown May 16 '12 at 11:09
Even with a SPSiteDataQuery, you should restrict the returned Rows Limit. Unless you're doing batch operation (at that scale ?) there is no usage of returning 1.000.000 items and you'll kill your WFE app pool memory. – Francois Verbeeck May 16 '12 at 11:15
If you get a million result then you'll run into problems unless you're using SharePoint server and can use ContentIterator – Per Jakobsen May 16 '12 at 11:18

Your Answer


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.