Conversion tagged posts

Convert an SPListItemCollection to an IEnumerable

Category: #SharePoint Comments: No comments

In one of my last project I make a function to accept an IEnumerable<T> as parameter. I normally used this function with PublishingPageCollection. This collection inherits fromĀ QueryBasedCollection<PublishingPage> and so it is a IEnumerable. Unfortunately the SPListItemCollection it is not.

I didn’t want to change my method and I didn’t want to create an overload only for the type of parameters. Then…I remembered that LINQ is my friend :)
You can directly convert an SPListItemCollection. Below an example…hope can help you…

using (SPWeb web = SPContext.Current.Site.OpenWeb("myweb"))
       return web.Lists["MyList"].Items.Cast<SPListItem>().Select(item => item);
Read More