in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, Office 365 / SharePoint Online and Visual Studio 2013.

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

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.

Published Mar 03 2008, 10:13 AM by CoreyRoth
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 said:

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

August 22, 2009 8:26 AM
 

Bobby Habib said:

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);

       }

September 17, 2012 5:58 AM

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an Applications Architect at Infusion specializing in ECM and Search.
2012 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems