I write a lot of code using the SharePoint object model. Often times, I want to check to see if a particular Web exists in a Site Collection or a List exists in a Web. I used to write methods that enumerated through the collection to see if they existed or I wrapped a Try-Catch block around the code in case the object didn’t exist.
Recently I came across a code snippet that made checking for the existence of a web or list easy. I can’t remember where I found it so I’ll thank the nameless person who originally wrote the code. I’m only capturing it here for my own reference and possibly help someone else.
static bool ListExists(SPWeb web, string listName)
{
return web.Lists.Cast().Any(list => string.Equals(list.Title, listName));
}
static bool WebExists(SPSite site, string webName)
{
return site.AllWebs.Cast().Any(web => string.Equals(web.Name, webName));
}
Leave a Reply