LINQ VS SPQUERY to Retrieve List Items

Nowadays, I’m getting used to query list using Linq instead of creating SPQuery object and use CAML to filter and retrieve list items. I did that because I’m lazy to generate the CAML query using CAML Designer. Below is example on how you retrieve list items using Linq and SPQuery

SPQuery

private SPListItem GetLatestResultForStudent(SPList listStudentResult, string name)
{
 string caml = string.Format(@"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='FALSE' /></OrderBy>", name);
 SPQuery query = new SPQuery();
 query.Query = caml;
 SPListItemCollection studentResults = listStudentResult.GetItems(query);

 if (studentResults.Count >= 1)
 {
  return studentResults[0];
 }
 return null;
}

LINQ

private SPListItem GetLatestResultForStudent(SPList listStudentResult, string name)
{
 SPListItem latestStudentResult = listStudentResult.Items.Cast<SPListItem>().Where(strslt => strslt["Title"].ToString() == name).OrderBy(apv => apv["Created"]).Last();
 return latestWorkflowCompleted;
}

Performance: CAML win !

What you guys think in terms of reading CAML query and LINQ where clause? I think both needs sometime to get used to. But recently I found technet article to explain both performance. One of the response is “In Linq, Code is converted to CAML under the hood resulting in a slight performance hit

Advertisements

Tagged: , , , , , , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: