Technical Fun

LINQ-ing SPListCollection

Posted on: January 3, 2008

After trying this LINQToSharePoint, I must admit I was a bit carried away in forcing Linq to my SharePoint programming needs.
I had this one very “not so important” ambition of iterating through SPList object within the SPListCollection on a SPWeb object.
Problem popped out, SPListCollection was not implementing IEnumerable, so I could not walk easily using Linq to this collection.
So.. to fulfill my ambition, I created a pseudo-adapter class which looked like this:

public class SPListCollectionAdapter : List<SPList>
{
private SPListCollection _listCol;

public SPListCollectionAdapter(SPListCollection listCol)
{
_listCol = listCol;

Refresh();
}

private void Refresh()
{
this.Clear();

foreach (SPList item in _listCol)
{
this.Add(item);
}
}
}

and shortly after that, I could then satisfy my quaint hunger with this method:

private static void DoMOSSLinq()
{
SPSite site = new SPSite(“http://titanctp2:9000&#8221;);
SPWeb web = site.AllWebs[0];

SPListCollectionAdapter listAdapter = new SPListCollectionAdapter(web.Lists);

var result = from l in listAdapter
select l;

foreach (var i in result)
Console.WriteLine(i.Title);

Console.ReadLine();
}

woohooo!!! I am no longer hungry.

3 Responses to "LINQ-ing SPListCollection"

Hi Asfar,

Intersting Post , I was wondering is there any different by doing same with following code ??? Lately I was trying to get hold of Linq and implement the same with SP to easy life. Please let me know.

SPListCollection oSPListCollection = SPContext.Current.Web.Lists;
var oHiddenLists = from SPList currentList in oSPListCollection
where currentList.Hidden == true
select currentList;

Thanks & Regards
Senthil

How about the .OfType() LINQ method? Requires less code.


private static void DoMOSSLinq()
{
SPSite site = new SPSite(“http://titanctp2:9000″);
SPWeb web = site.AllWebs[0];

var result = from l in web.Lists.OfType()
select l;

foreach (var i in result)
Console.WriteLine(i.Title);

Console.ReadLine();
}