Tuesday, 25 May 2010

Accessing SharePoint List Data using Linq

Recently I wanted to return a SharePoint list as an List<> of a business object.

I did some scouring on the internet, as there is no point re-inventing the wheel.  But was generally disappointed with the results, as they required a lot of iterations and loops. Eric White’s blog here got me thinking, that we could do it with Linq

So here is what I did Projects my business object looks like this

Property Data Type
ProjectOwner string
KPI string
SKU string
DateRequired DateTime?
DueDate string
   

And here is the code, which expects a result set from a Sharepoint Web Service GetListItems() method.

Code Snippet
  1. private static List<ProjectStatus> GetProjectStatusesFromXmlNode(XmlNode resultNode)
  2.     {
  3.         var list = (from r in resultNode.GetXElement().Descendants()
  4.                     where r.Name.LocalName == "row"
  5.                     select new ProjectStatus
  6.                     {
  7.                         Project = (string)r.Attribute("ows_LinkTitle"),
  8.                         DateRequired = DateTime.Parse(((string)r.Attribute("ows_DateRequired"))),
  9.                         DueDate = (string)r.Attribute("ows_ECRDueDate"),
  10.                         SKU = (string)r.Attribute("ows_SKU"),
  11.                         Status = (string)r.Attribute("ows_Status"),
  12.                         ProjectOwner = (string)r.Attribute("ows_AssignedTo"),
  13.                         KPI = (string)r.Attribute("ows_tKPI")
  14.                     }
  15.                     ).ToList();
  16.         return list;
  17.     }

You will also need Eric White’s extension

Code Snippet
  1. public static class Extensions
  2. {
  3.     public static XElement GetXElement(this  XmlNode node)
  4.     {
  5.         XDocument xDoc = new XDocument();
  6.         using (XmlWriter xmlWriter = xDoc.CreateWriter())
  7.             node.WriteTo(xmlWriter);
  8.         return xDoc.Root;
  9.     }
  10.  
  11. }

No comments:

Post a Comment