A new way of retrieving lists in SharePoint 2010

Just found of a new method within the SPListCollection object that season WSS 3.0 devs will appreciate a lot. In WSS 3.0, there’s not really a neat way to get an instance of a list that might not exist.

I usually use SPList myList = web.Lists[listName]; but it throws a null reference error if the list is not there. Looping through the SPListItemCollection object is usually how we’ll check for a list instance, but I think its a waste of resources.

In SharePoint 2010, a new method “TryGetList” is implemented to get the list and it throws a null refernce if it doesn’t find it.

using (SPWeb web = site.RootWeb)
{
 SPList myList = web.Lists.TryGetList("My List Name");
 if (myList != null)
 {
  ...
 }
}

I’m excited to get my hands dirty in SP2010, I hope incoming projects will be based on it.

Popularity: 14%

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>