Checking to see if a list item exists in SharePoint 2010

Posted Wednesday, October 21, 2009 11:02 AM by CoreyRoth

This is another topic that is quite dear to most SharePoint developers.  We’ve all been there.  We want to know if a list item exists and the indexer is useless.  It throws an exception should we attempt to access an item that does not exist.  Well as we discovered this week there is a new TryGetList method that works great to determine if a list exists but there really isn’t anything new with a SPBaseCollection.  We can do this a number of ways include spmetal.exe to generate strongly typed classes, but I was looking for a solution that didn’t require me to generate any classes.  We can now use .OfType<T> to get an IEnumerable<T> that we can use.  Once we have IEnumerable<T> it is quite easy to determine if a list item exists using the .Any() method.  Look at the example below.

using (SPSite siteCollection = new SPSite("http://moss-server"))

{

    SPList myCustomList = siteCollection.RootWeb.Lists.TryGetList("MyCustomList");

 

    // doesn't throw exception!

    if (myCustomList != null)

    {

        var listEnumeration = myCustomList.Items.OfType<SPListItem>();

        return listEnumeration.Any(p => p.Name == "List Item 1");

    }

}

As you can see using the lambda expression p => p.Name we can do a comparison to see if a list item with that name exists.  This will return us a boolean if the item does in fact exist.  As you can see this isn't quite as good as a native method that checks for an item that exists, but it does work.  If you want to get creative you can also check on other fields such as Title, Id, or whatever.  Take a look at this sample.

listEnumeration.Any(p => p["Title"] == "List Item 1");

listEnumeration.Any(p => p.UniqueId == someGuid);

As you can see, LINQ makes it quite easy to determine if an item exists.  This may not be the most efficient way to do it as it is rather brute force.  It may only be arguably better than using a try / catch block, but it certainly looks cleaner.

Comments

# re: Checking to see if a list item exists in SharePoint 2010

Monday, September 13, 2010 5:25 PM by Bobby Habib

Better Way is to do the following:

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

using extension methods.

# re: Checking to see if a list item exists in SharePoint 2010

Monday, December 1, 2014 7:50 AM by Mark Kamoski

How can one check if a List item exists by using JavaScript or (if necessary) jQuery?

# re: Checking to see if a list item exists in SharePoint 2010

Monday, December 1, 2014 3:25 PM by CoreyRoth

@Mark query the list with REST and $.ajax.  If the $filter parameter you use doesn't match any items, you won't get any results in the response.

# re: Checking to see if a list item exists in SharePoint 2010

Thursday, December 11, 2014 12:09 AM by Shilpa

Good Article. It helped :)

Leave a Comment

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