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

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.

share|improve this question
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. –  Stuart Pegg Jul 17 '13 at 8:24
    
Idd, my bad. I'll remove it –  Ruben Herman Jul 17 '13 at 8:27

2 Answers 2

up vote 4 down vote accepted

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)
            {
                try
                {
                    yield return site;
                }
                finally
                {
                    site.Dispose();
                }
            }
        }
    }

Usage:

IEnumerable<SPSite> allTeamSites = currentWebApp.Sites.AsSafelyDisposed().Where(x => x.RootWeb.WebTemplateId != 4).OrderBy(x => x.RootWeb.Title);
share|improve this answer
    
And what about the web? Since we use it also to get the properties –  Ruben Herman Jul 17 '13 at 9:46
2  
You don't need dispose for getting the RootWeb properties. –  Falak Mahmood Jul 17 '13 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.

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.