TryGetView SPList extension


Extension methods are a new feature in .NET 3.5 and I think they are brilliant to extend existing classes. I’m not going to talk about them any more in detail here, but if you wish to find out more about them you can find them at the following Microsoft link.

http://msdn.microsoft.com/en-gb/library/vstudio/bb383977.aspx

To find a list in a given SPWeb you have a couple of options, by ID of the list, by the index of the list collection, by the name of the list. The one I like to use is:

SPList myList = SPContext.Current.Web.Lists.TryGetList("My Custom List");

The reason why I like to use this code is that if it is unable to find the list it returns a null value. Here is where I think Microsoft has missed a trick, why isn’t there SPList.TryGetView(“My View”)? There is an easy way of creating it by using extensions.

public static class Extensions
{
  public static SPView TryGetView(this SPList spList, string viewName)
  {
  return spList.View.Cast<SPView>()
               .Where(view => !view.Hidden)
.FirstOrDefault(view =>
                String.Compare(view.Title, viewName, String.Comparision.OrdinalIgnoreCase) == 0)
  }
}

The above extension will allow you to search for a view by name on a given list, and return null value if it cannot find the view.

Advertisements