Using LINQ in Sharepoint Object Model

I have been playing around with LINQ in Sharepoint object model and I have to say I’m quite impressed. It does shorten the amount of code we write and works just as great or better.

For example, one of the most common ways to query a list of objects was to use a foreach loop:

SPSite site = new SPSite(http://server/site);
foreach (SPList list in site.AllWebs[0].Lists){
if (list.Hidden)
hiddenLists.Add(list);
}

Now, by using LINQ, we only have to write fewer lines of code:

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

Same if we want to query a field in a list:

SPFieldChoice oField = myList.Fields[FIELDNAME];
var OrderedChoices = from oChoice in oField.Choices orderby oChoice ascending select oChoice

Pretty neat huh!

Now, we can use LINQ to replace any CAML query as well, it works really well!!

Say, if we want to query a list, where the field “User” is not null and we want to order the result by Title ascending.

To do it with CAML query, one would have to do this:

SPList oUserList = myWeb.ParentWeb.Lists[“UserList”];
string strQuery = “<Where><IsNotNull><FieldRef Name=\”User\” /></IsNotNull></Where> <OrderBy><FieldRef Name=’Title’ Ascending=’True’ /></OrderBy>”;
SPQuery spQuery = new SPQuery();
spQuery.Query = strQuery;
SPListItemCollection result2 = oUserList.GetItems(spQuery);

If we use LINQ, we only have to do this:

var sortedUsers = from SPListItem sortedUser in oUserList.Items
where sortedUser[“User”] != null
orderby sortedUser.Title ascending
select sortedUser;

Which is a lot more human readable!!

Categories: Sharepoint 2007
Tags: