Friday, October 9, 2009

How to check if list is a document library ? Let's Linq it !

Sometimes you need to iterate via the Doclibs of a site for a dedicated reason, and there is no need to iterate via the "regular" lists of the site.

Of course it's very easy so you usually just run something like that -

 
SPWeb web = site.Openweb();
SPListCollection listCol = web.lists;
foreach(SPList list in listCol )
{
//Do your thing
}


So in order to be more efficient, run only in doclibs, and not on all lists that you have in your website ( including hidden ones ).

How you do that ? very simple.

 
SPWeb web = site.Openweb();
SPListCollection listCol = web.lists;
foreach(SPList list in listCol )
{
if(list.BaseType == SPBaseType.DocumentLibrary)
{
//Do your thing
}
}


And to make it even nicer, lets just LINQ it -
 
var docLibs = from SPList list in web.Lists where (list.BaseType == SPBaseType.DocumentLibrary) select list;
foreach (SPList doclib in docLibs)
{
//do your thing
}


Hope it helps.

No comments:

Post a Comment