Using an Extension Method to check if an item exists in a SharePoint collection

Posted Monday, March 3, 2008 10:13 AM by CoreyRoth

As I have mentioned before, one of my biggest complaints about SharePoint is that none of the collections in the SharePoint API have any way to determine if an item exists.  Extension Methods offer a slightly more elegant way to do this, although the underlying code still violated multiple best practice rules.  Take a look at this example using the SPFileCollection.

public static bool Contains(this SPFileCollection fileCollection, string index)

{

    try

    {

        SPFile testFile = fileCollection[index];

        return true;

    }

    catch (SPException e)

    {

        return false;

    }

}

If you're not familiar with Extension Methods yet, they are an addition in C# 3.0 that allow you to add methods to existing classes without having to inherit from them.  You prefix the first parameter with the keyword this followed by a type to specify what type you are extending.  You can put your extension method in any class you want.  Inside, the method, you see the typical way of checking to see if something exists in a SharePoint collection: try/catch.   The syntax for using the extension method is below.

bool fileExists = fileCollection.Contains("SomeFile");

Extension methods are quite powerful and I think they can provide an excellent way to make many tasks easier and cleaner inside the SharePoint API.

Filed under: ,

Comments

# Twitter Trackbacks for Using an Extension Method to check if an item exists in a SharePoint collection - Corey Roth - [dotnetmafia.com] on Topsy.com

Pingback from  Twitter Trackbacks for                 Using an Extension Method to check if an item exists in a SharePoint collection - Corey Roth -         [dotnetmafia.com]        on Topsy.com

# re: Using an Extension Method to check if an item exists in a SharePoint collection

Monday, September 17, 2012 5:58 AM by Bobby Habib

With extension methods you could use the following line without forcing a exception. Bad Practice.

public static bool ListExists(this SPWeb web, string listName)

       {

           return web.Lists.Cast<SPList>().Any(list => string.Compare(list.Title, listName, true) == 0);

       }

Leave a Comment

(required) 
(required) 
(optional)
(required)