SharePoint: SPList.HasView() extension method
One quick posting. I wrote yesterday extension method for SharePoint that checks if view exists. I think it is far better for performance if I don’t live on try…catch to find out if view exists or not. Extension method that you have to put in static class is here.
C#
/// <summary>
/// Determines whether the specified list has view with given name.
/// </summary>
/// <param name="list">The list to search from.</param>
/// <param name="viewName">Name of the view.</param>
/// <returns>
/// <c>true</c> if the specified list has view; otherwise,
/// <c>false</c>.
/// </returns>
[CLSCompliant(false)]
public static bool HasView(this SPList list, string viewName)
{
if(string.IsNullOrEmpty(viewName))
return false;
foreach(SPView view in list.Views)
if(view.Title.ToLowerInvariant() ==
viewName.ToLowerInvariant())
return true;
return false;
}
VB.NET
''' <summary>
''' Determines whether the specified list has view with given name.
''' </summary>
''' <param name="list">The list to search from.</param>
''' <param name="viewName">Name of the view.</param>
''' <returns>
''' <c>true</c> if the specified list has view; otherwise,
''' <c>false</c>.
''' </returns>
<CLSCompliant(False)> _
<System.Runtime.CompilerServices.Extension> _
Public Shared Function HasView(ByVal list As SPList, _
ByVal viewName As String) As Boolean
If String.IsNullOrEmpty(viewName) Then
Return False
End If
For Each view As SPView In list.Views
If view.Title.ToLowerInvariant() = _
viewName.ToLowerInvariant() Then
Return True
End If
Next
Return False
End Function