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.