Friday, October 12, 2012

SharePoint & Linq: More with less

Linq makes it easy to navigate thru a record set object of SharePoint List items.

// Using Statement

using System.Linq;

// Build the Query Object
SPQuery queryObject = new SPQuery();
queryObject.Query = 

@"<where>
   <contains>
      <fieldref name="FirstName">
         <value type="Text">Bob</value>
      </fieldref>
   </contains>
</where>
<orderby>
   <fieldref ascending="TRUE" name="Modified">
   </fieldref>
</orderby>";
Now, here's where the magic starts
Super Linq! -  Retrieving list items with a single line of code!

var results = list.GetItems(queryObject).Cast<splistitem>();


// Here's how to see if any records were returned
if (!results.Count().Equals(0))

// Want just the Last record?

var resultItem = list.GetItems(queryObject).Cast<SPListItem>().Last();

// Want just the First record?
var resultItem = list.GetItems(queryObject).Cast<SPListItem>().First();

No comments:

Post a Comment