Most SharePoint objects (Microsoft.SharePoint.dll) contain typed collections to store the references to other objects (example: SPList.Items is an SPListItemCollection). The problem is, that these collections implement methods for retrieving objects from these collections that throw ArgumentExceptions if the key-value (unique value: i.e. title, GUID, id, index) does not retrieve a valid element.
If you have a typical update method that has to check if the underlying object exists you will do it using one of the following two possibilities:
public static SPList GetElementTry(SPWeb web, string listName)
{
SPList list = null;
try
{
list = web.Lists[listName];
}
catch(Exception) {}
return list;
}
public static SPList GetElementIterate(SPWeb web, string listName)
{
SPList list = null;
string listName = listName.ToLower();
SPListCollection lists = web.Lists;
foreach(SPList list in lists)
{
if(string.Equals(list.Title.ToLower(), listName))
{
return list;
}
}
return list;
}
The problem now is: which one is better from a performance and design point of view?
I read somewhere that in Java (I used to develop in Java) if you want a basic metric (and this is a strong abstraction from reality, if it is even applicable) you can say the creation and throwing of an exception costs about 400 times more than a basic comparison (and again, please correct me if I’m wrong in this assumption).
The SharePoint magic number of storage / items / lists / objects: 2GB // 2000.
When you compare this to 400, then you will probably end up saying: I can optimize iteration a little bit so I’ll use this, because it seems more elegant, but I would rather have an internal method that does this for me and instead of throwing an exception it returns null.
Well we’re not in happy-land so you have to make a decision.
Something I would not do though is implement a method ElementExists that does the same thing as the Get-method and instead of returning null / the element it just returns true/false. You can check for null in your code instead, if you encapsulate with a boolean value you need to call your method twice. This is only sensible if you do not need to use the object further.
On how to iterate, check this blog.