dinsdag 8 januari 2013

SPListItemCollection with Linq

I like to use linq to find, sort, .. items in a list quick and easily, but it’s a pain to convert a SPListItemCollection into a generic list. Today I wrote a class that do the conversion for me easily.

Code Snippet
  1. public class SPListItemCollectionAdapter : List<SPListItem>
  2.     {
  3.         private SPListItemCollection _listItemCollection;
  4.  
  5.         /// <summary>
  6.         /// Get a generic list of SPListItems and convert it
  7.         /// </summary>
  8.         /// <param name="listItemCollection">SPListItemCollection collection of items</param>
  9.         public SPListItemCollectionAdapter(SPListItemCollection listItemCollection)
  10.         {
  11.             _listItemCollection = listItemCollection;
  12.  
  13.             Refresh();
  14.         }
  15.  
  16.         /// <summary>
  17.         /// Convert a SPListItemCollection into a generic list
  18.         /// </summary>
  19.         private void Refresh()
  20.         {
  21.             this.Clear();
  22.  
  23.             foreach (SPListItem item in _listItemCollection)
  24.             {
  25.                 this.Add(item);
  26.             }
  27.         }
  28.     }

Now you can use the class above like:

Code Snippet
  1. private SPListItemCollectionAdapter GetItems(SPList list, string query)
  2.         {
  3.             SPQuery q = new SPQuery();
  4.             q.Query = query;
  5.  
  6.             return new SPListItemCollectionAdapter(list.GetItems(q));
  7.         }

The only thing you need to do is declare a variable of the type SPListItemCollectionAdapter and create a new one.

Isn’t it easy?