Wednesday, September 21, 2011

Inbuilt method to Check if List Exist in SharePoint 2010.

In SharePoint 2007, one of the mostly required methods but not provided by Microsoft:
Checking if SharePoint List exists on Site or not?
If we directly use spWeb.Lists[“<ListName>”] and if list does not exist then it will throw an exception. To avoid such exceptions I have created following extension method:
public static bool IsListExists(this SPWeb spWeb, string listName)
{
    try
    {
        return spWeb.Lists.Cast<SPList>().Any(list => string.Compare(list.Title, listName, true) == 0);
    }
    catch (Exception ex)
    {
        ex.LogException("List does not exist", CommonConstants.EVENT_SOURCE, spWeb, spWeb.CurrentUser);
        return false;
    }
}
Now Microsoft is woke up, In SharePoint 2010 they have provided an inbuilt method method in the SPListCollection .Simply use this method instead of looping all the lists and check its existence.

SPList sampleList = spWeb.Lists.TryGetList("SampleList");
if (sampleList != null)
{
    // Code Block goes here
}

Hope this helps you...

3 comments: