Result Shaping Using LINQ
One
of the benefits of LINQ is its ability to shape result sets while still
retaining a type-safe output. We can explore this functionality by
adding another button to our sample application; this time, label it Basic Result Shaping and add the following code:
private void button7_Click(object sender, EventArgs e)
{
using(HireSampleDataContext dxRead = new HireSampleDataContext(SiteUrl.Text))
{
//create a stringbuilder to store the CAML query
StringBuilder sb = new StringBuilder();
using (StringWriter logWriter = new StringWriter(sb))
{
//log the generated CAML query to a StringWriter
dxRead.Log = logWriter;
dxRead.ObjectTrackingEnabled = false;
var basicQuery = from c in dxRead.HireContracts
where c.ContractStartDate.Value < DateTime.Now
orderby c.ContractStartDate
select new{
c.ContractId,
c.ContractStartDate,
c.ContractEndDate,
Creator = c.DocumentCreatedBy.Substring(
c.DocumentCreatedBy.LastIndexOf(‘\\’)+1),
Version = "v" + c.Version.Value.ToString("0.000")
};
dataGridView1.DataSource = basicQuery.ToList();
}
string fileName = Path.Combine(Path.GetTempPath(), "tmpCaml.xml");
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
doc.Save(fileName);
//point the browser control to the temporary generated CAML file
webBrowser1.Navigate(fileName);
}
}
Notice the creation of a new anonymous type as part
of the LINQ query. The new type consists of fields from the returned
entity together with some string manipulation functions to get the
results into the appropriate format.
Notice when examining the generated CAML
for this query that the string manipulations have not been translated.
Although CAML does not support these operations, the LINQ to SharePoint
provider still allows them as part of the query because they are
performed on the results and are therefore unlikely to cause
significant performance issues.