I'm wondering if this needs to be disposed or if it's a bad method to get the title of a web.

var currentWebApp = SPContext.Current.Site.WebApplication;
IEnumerable<SPSite> allTeamSites = currentWebApp.Sites.Where(x => x.RootWeb.WebTemplateId != 4).OrderBy(x => x.RootWeb.Title);

This because we get the WebTemplateId and the Title of the rootweb of a site without opening the web.

  • 1
    Side notes: The currentSite variable isn't used in this sample, and you can use .Select(w => w.Title) if you just want the titles.
    – Stu Pegg
    Jul 17, 2013 at 8:24
  • Idd, my bad. I'll remove it Jul 17, 2013 at 8:27

2 Answers 2


Yes, SPSite needs to be disposed

But you can handle the disposal of SPSite through the enumerator using the extension method (see below):

 static class Extensions
        public static IEnumerable<SPSite> AsSafelyDisposed(this SPSiteCollection sites)
            foreach (SPSite site in sites)
                    yield return site;


IEnumerable<SPSite> allTeamSites = currentWebApp.Sites.AsSafelyDisposed().Where(x => x.RootWeb.WebTemplateId != 4).OrderBy(x => x.RootWeb.Title);
  • And what about the web? Since we use it also to get the properties Jul 17, 2013 at 9:46
  • 2
    You don't need dispose for getting the RootWeb properties. Jul 17, 2013 at 9:50

What do you do with your IEnumerable after?

Most uses of that enumeration will re-open the SPSites. IMHO it is not good practice to create enumerables or lists of SP* objects, unless you deal with the dispose in the same scope.

You should change your LINQ to select into a new object with only the members of SPSite that you actually want to use. If you want to use any methods on it, you will need to revisit your strategy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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