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?
views:
675answers:
1
+1
Q:
Is there any way to check for the existence of an SPList or SPListItem without a try/catch block?
+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
2009-09-03 19:34:29
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
2009-09-07 18:08:32
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
2009-09-07 18:44:02
Just to confirm then - the line should then read(from list in web.Lists.Cast<SPList>() where ... )?
Ryan Shripat
2009-09-08 15:18:15
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
2009-09-08 16:52:12