kamagra how much to take

Best Practice: Don’t Iterate SPListItems for IQueryable Support

I saw this during a code review today. Essentially, to support a LINQ query into a SPListItemCollection, there was an iteration that converted the SPListItemCollection to a typed List collection, the secondary collection subsequently being queried through LINQ. While SPListItemCollection implements IEnumerable it is challenging to use when converting the instance to IQueryable because it will fall back on IEnumerable specification since it simplements IEnumerable, not IQueryable.

The method in question looked like this:

public static List ConvertToTypedList(SPListItemCollection collection)
List items = new List();
foreach (SPListItem item in collection)
return items;

That iteration IMHO is entirely too expensive for performance reasons because of dual collection builds, and it’s just plain ugly. For each query run, execute collection generation of an already existing collection? No thanks! :)

Instead, just use Cast(), it’s much cleaner and this is the exact situation it is used for. Replicating the intent of the above iteration, I can simply express in the domain terms (via method chaining) the LINQ query (which you can obviously modify with whatever query you like).

var results = SPContext.Current.Web.Lists[“Some List”].Items.Cast().Select(item => item);
For example, to using a where clause for a specific title:
var results = SPContext.Current.Web.Lists[“Some List”].Items.Cast().Where(item => item[SPBuiltInFieldId.Title].ToString() == “Title To Search”);



  1. Oz Ortiz says:

    As a side question, do you think it’s better to use a LINQ query into an SPListItemCollection rather than using a CAML query (as in an SPQuery object)?

  2. Adam Buenz says:

    Hmmm, I prefer the LINQ query simply because everything is strongly typed, as opposed to relying on a string literal which is easier to mess up. I am not sure of the performance differences though.

  3. Mauro says:

    A CAML query is executed on the server and provides a smaller list, a LINQ query is executed on the client (possibly a web part, or a windows app) but requires the full list to then filter out – this means in theory you could be sending a LARGE SPListItem collection over the network to a client to filter when the work could already be done by the server for you – resulting in less network traffic. However, each approach has its benefits/drawbacks and should be weighed up against the specific needs of the solution


  1. Links (12/4/2008) « Steve Pietrek - Everything SharePoint - [...] Best Practice: Don't Iterate SPListItems for IQueryable Support [...]
  2. Safely Process SPSite.AllWebs « Solutionizing .NET - [...] Speaking of LINQ and SharePoint, check out Adam Buenz’s post on using LINQ’s IEnumerable.Cast<T> with SharePoint collections to get…

Leave a Reply

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