Friday, September 17, 2010

LINQ Queryable SharePoint Collection

Today I ran into the need to bind the items in a SharePoint list to an asp:ListView control. While it was possible to use the SPListItemCollection as the DataSource for the control, it was made complicated by a "Hyperlink or Picture" column I was using in the list. When returned, that column would return as a single value in the format "{URL}, {DisplayText}". If I wanted to use the SPListItemCollection, it meant my ASCX page would be cluttered with string parsing, instead of a nice, clean <%# Eval("Link") %>.

I decided I would use LINQ to build the collection to bind to my ListView. Doing such, would allow me to move all the string parsing out of the front-end and into my classes. The only problem is that SharePoint collections are not queryable. A quick Google search, took me to a blog post by Asfar Sadewa,
Direct Linq to SPListItemCollection. Then I thought, why not make this generic so that it can be applied to all SharePoint collections? Below is the result:

public class QueryableSharePointCollection<C, T> : List<T> where C : SPBaseCollection
{
public QueryableSharePointCollection(C sharepointCollection)
{
this.Clear();

foreach (T item in sharepointCollection)
{
this.Add(item);
}
}
}

Now I just have to instantiate a new QueryableSharePointCollection, specifying the collection type, and the type of the items in the collection, and I have a queryable collection derived from a SharePoint collection.