Wednesday, October 11, 2006

Using LINQ with SharePoint List Data


Ever since I sat in on one of Anders Hejlsberg's TechEd sessions about LINQ a while back, I've been wanting to take a look at how to use LINQ with SharePoint List data. Well, timing and priorities have kept me from diving in, but Kevin Hoffman has started the ball rolling with this post about using LINQ with SharePoint.

What is LINQ and why use it with SharePoint List data? Well, LINQ stands for Language Integrated Query, and what LINQ does is add a native querying syntax reminiscent of SQL to .NET Framework programming languages. To illustrate why using LINQ with SharePoint is a compelling approach to programming against List data, I'll borrow a few code snippets from Kevin Hoffman's post:

First, the usual method for enumerating List data:

1 SPSite site = new SPSite("http://server/site");
2 SPWeb web = site.AllWebs[0];
3
4 List<SPList> hiddenLists = new List<SPlist>(); // Do not use an SPListCollection here
5 foreach (SPList list in web.Lists)
6 {
7 if (list.Hidden)
8 hiddenLists.Add(list);
9 }

Now, the same thing with LINQ:

1 SPSite site = new SPSite("http://server/site");
2 SPWeb web = site.AllWebs[0];
3
4 var hiddenLists = from list in web.Lists where list.Hidden select list;

Half the code, and good-bye foreach loop! Elegant, no? Take a look at Kevin's post for more details. Thanks for the info Kevin. I'm not sure what book you're working on, but good luck!

Categories: , , , , , ,

Post a Comment