views:

675

answers:

1

In SharePoint, I'd like to be able to check if a particular List or ListItem exists before performing operations on it, but there doesn't seem to be a way to do this without simply catching an ArgumentException. Surely there's a better way?

+4  A: 

To find an instance of a SPList you could use a linq solution:

SPList instance = (from SPList list in web.Lists   
                   where list.RootFolder.Name.Equals(name) 
                   select list).FirstOrDefault();   

if (instance != null)   
{
...// process

A similar solution could be made for find an instance of a SPListItem

FirstOrDefault is the trick. Default is null (not an exception).

UPDATE:

as a comment, this line of code:

from SPList list in web.Lists

is the same as writing

from list in web.List.Cast<SPList>
Johan Leino
web.Lists (an SPListCollection) is not an IEnumerable, so your code above will not work as is. "from SPList list in web.Lists.Cast<SPList>() where ..." would work though. Could you update your answer to include this, and then I'll mark it as the Accepted Solution?Thanks!
Ryan Shripat
My experience is that the code "from SPList list in web.List" is the same as writing "from list in web.List.Cast<SPList>". When you explicitly include the type (SPList) like this a call to Cast<SPList> is made behind the scenes which indeed needs to be made because the SPListCollection does not implement IEnumerable<SPList> as you said. With that said, you shouldn´t include the type if the collection you enumerate indeed implements IEnumerable<T> because then you wouldn´t need or want to call Cast<T>
Johan Leino
Just to confirm then - the line should then read(from list in web.Lists.Cast<SPList>() where ... )?
Ryan Shripat
It doesn´t matter. That line is the same as writing from SPList list in web.Lists. It will translate(compiler stuff probably) to from list in web.Lists.Cast<SPList>....which in turn will translate into a lambdaexpression
Johan Leino