Thursday, November 12, 2009

CAML Vs Linq ? What's better ?

A few days ago I had a small project over one of my clients, one of the issues I had to deal with was to iterate via his enormous lists sizes, and to change specific MetaData according to other metadata that he already has.

Then I had to choose how I want to work with those lists

Why Linq ?

1. Easy for the .net developer, no new skills required.
2. intellisense. It's a great deal sometimes.
3. Easy to read your code, no loops, no "weird" syntax.
4. Can combine multiple sources ( XML files, SharePoint lists and databases and more ... )

Why NOT Linq ?

1.Performance issues in some cases. All items are being retrieved from the database.
The filtering phase is being done only by iterating via all all items and comparing them to the where clause. So in large collections we have a major performance problem with Linq.

An example, which we will use later again :

 
//checking if the column address is not empty and the column name equals tothe filter.
//and order it by PostedOn

var resourceListItems = fromSPListItemitemin resourceList.Items
whereitem[“Name”] .ToString().ToLower().Contains(_filter)
&& item[“Adress”].ToString().Length> 0
orderbyitem[“PostedOn”] ascending


Why CAMAL ?

1. Only items that match the filter criteria will be retrieved from the database.
2. There are some wizards to make it easier for writing those queries ( such as : LinqToSharepoint, Linq4SP and some more - just google those names ).

Why NOT CAMAL ?

1. Syntax. No intellisense. Not easy to read.
2. Problematic filtering, not as wide as you can get in Linq. If you want to compare two columns it's not feasible ( I might wrong on that ).

Same example as before in CAML :

 
//checking if the column address is not empty and the column name equals tothe filter.
//and order it by PostedOn, and at last calling getting the collection.

SPQueryquery = newSPQuery();
query.Query= String.Format(“

{0}




”, _filter);

SPListItemCollectionlistItemsColl= resourceList.GetItems(query);


And yes, you can use them both combined , for example :

 

SPQuerycamlQuery= newSPQuery();
camlQuery.Query= String.Format(“

{0}


”, _filter);
var resourceItemsCollection=fromSPListItemiteminresourceList.GetItems(camlQuery)
orderbyitem[“PostedOn”] ascending


Bottom line, it depends on what you need to do :

If you work on a very large collection, you better use CAMAL ( also recommended in the MSDN ).

If you work on a small collection , and the cost of iterating all collection is ok for you, Or when you need to make a certain filtering that requires iteration ( such as column comparison ) then choose Linq.

Enjoy.

No comments:

Post a Comment