Tuesday 19 May 2009

Linq to XMl Joins

Here is an example of a left join:

var joinXml = from m in result.Descendants("Report")
join o in ordered.Descendants("Report")
on (string)m.Attribute("name").Value.ToLower()
equals (string)o.Attribute("name").Value.ToLower()
into mainGroup
let orderedMatch = (
from x in mainGroup.DefaultIfEmpty()
where x != null
select new XElement("Report",
new XAttribute("name", m.Attribute("name").Value),
new XAttribute("trend", "true"))
)
let orderedNoMatch = (
from y in mainGroup.DefaultIfEmpty()
where y == null
select new XElement("Report",
new XAttribute("name", m.Attribute("name").Value),
new XAttribute("trend", "false"))
)
let total = orderedMatch.Concat(orderedNoMatch)
select total;

Wednesday 13 May 2009

LINQ to XML

Below is an example of how I used LINQ to XML to read an XML string and search for nodes that match a criteria within the tree. It also shows how I order by an attribute.

The XML:



The Code: