SharePoint List Querying – Linq vs. CAML
One of the nice features of SharePoint 2007 development is the ability to use the latest release of the .NET framework and its concomitant language features – including Linq. This in and of itself it a huge benefit as the inherit query mechanism within SharePoint – CAML is woefully terrible.
What is CAML? A pain in the arse. Officially, it stands for Collaborative Application Markup Language – which amounts to more bollox than telling you anything you need to know. Essentially, CAML is an xml structured intermediate query syntax for SharePoint to query against data structures (that can also be defined using CAML). Sounds a bit like SQL no? Well guess what CAML gets translated to in the back-end? Yep – SQL. SharePoint takes your CAML and queries against its sql backend. So in short, with CAML you have this massively verbose query syntax that requires nested xml tags, multi-line statements, and quoted attributes – yuck!
Enter Linq, with its terse sql-esque statements and amazing chainability. Yay! No more CAML!!
Not quite.
Linq can only be used against a SPListItemCollection object which must be filled before use. The two most common ways to populate a SPListItemCollection is to either Get all items, or use a SPQuery object and CAML syntax to get a subset of items. As you can see, the dilemia presents itself that if you try to avoid CAML altogether, you will sacrifice performance when querying a list with potentially a large set of items.
So the best solution? Use both. Before using Linq directly to query items, first populate your SPListItemCollection with a CAML query that will do an adequate job of ensuring a manageable subset returned from the database. Then with Linq, fine-tune your SPListItemCollection to further sort and filter your result set. So Caml – Chainsaw, Linq – Carving Knife.
For more information, check out the excellent resource below:
LINQ and SharePoint Development: The benefits and the pitfalls
