Friday, May 15, 2009

Using LINQ in Sharepoint along side CAML

Using LINQ is a huge advantage when programming. It gives you great flexiblity with minimal code.
CAML is a fastest way to get your data from SharePoint, problem is that building a dynamic CAML query can be rather tedious, hard to read and error prone.

So the solution:

First you should get the Dynamic library from ScottGu's Blog.

Now to get your list items you can run your CAML to do as much as possible, ie return the list items sorted by modified date, filtered by Content Type and maybe bring back a specific number of items (though in this example I cannot specify the RowLimit on my SPQuery as I need the full list to further filter from).

Then if you have further parameters that you need to filter on, ie multiple drop down lists that a user may or may not select, then you can employee LINQ as below:

            
//Get your list collection ordered and filtered as much as you can using CAML
SPListItemCollection listCollection = web.Lists[listName].GetItems(query);

//check that user is filtering by both industry and country
if (IndustryItem != null && countryItem != null)
{

listItems = listCollection.Cast<SPListItem>()
.Where(p => (p.GetFormattedValue("Country").Contains(countryItem.Title) && p.GetFormattedValue("Industry").Contains(industryItem.Title)))
.Take(5);
}


Of course you would require a few more else if blocks depending on the number of options to filter on but as you can see alot easier to achieve it this way then using just CAML.

No comments:

Post a Comment