|
There is no .Exists() method off of SPWeb and so it is hard to check whether a list exists. The most efficient way to do this is the following: public static bool ListExists(SPWeb web, string listName) { return web.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, listName)); } Source: What Are The Biggest SharePoint API Mistakes? by Adam Buenz An alternative way is to use Extension methods (C# 3.0 feature) and extend the SPWeb object with a ListExists method like this: public static class Extensions { public static bool ListExists(this SPWeb web, string listName) { return web.Lists.Cast<SPList>().Any(list => string.Compare(list.Title, listName, true) == 0); } } Note that this extension method also does a case-insensitive comparision of the list title. Now this can be used like this: using (SPSite site = new SPSite("http://server/")) { using (SPWeb web = site.OpenWeb()) { Console.WriteLine("List {0} exisits? {1}", args[0], web.ListExists(args[0])); } } Labels |
Checking whether SPList Exists - workaround as List.Exist() method doesn't exist!

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License. Hosted generously by CustomWare









Comments (4)
Mar 06, 2009
Joe Breen says:
This is not explained enough. For clarity it would be useful if you explained w...This is not explained enough.
For clarity it would be useful if you explained what "list" should be in the code because if you copy and past this into Visual Studio it highlights an error:
public static bool ListExists(SPWeb web, string listName)
{
return web.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, listName));
}
Mar 08, 2009
Jeremy Thake says:
What is the error you are getting in Visual Studio exactly? This is actually us...What is the error you are getting in Visual Studio exactly?
This is actually using LINQ which will require .NET 3.5 to be configured for the Visual Studio project. Maybe this is the error you are getting?
Mar 13, 2009
Schalk van Wyk says:
Cool method, one has to remember it works with .NET 3.5 and you have to add the ...Cool method, one has to remember it works with .NET 3.5 and you have to add the using System.Linq namespace.
Any more methods out there that's helpfull, e.g. a generic method for getting the typecasted value of a field
May 12
Flippsie says:
Nice bit of Ninja coding, but why do I get a compile error stating that the Micr...Nice bit of Ninja coding, but why do I get a compile error stating that the Microsoft.SharePoint.SPListCollection does not contain a definition for the Cast method you are calling?