Given the following Xml fragment:
<root>
<sheetData>
<row r="1" />
<row r="2" />
<row r="3" />
<row r="4" />
<row r="5" />
<row r="6" />
<row r="7" />
</sheetData>
</root>
Which can be created with the following code:
XElement testElement = new XElement("root",
new XElement("sheetData",
new XElement("row",
new XAttribute("r", 1)),
new XElement("row",
new XAttribute("r", 2)),
new XElement("row",
new XAttribute("r", 3)),
new XElement("row",
new XAttribute("r", 4)),
new XElement("row",
new XAttribute("r", 5)),
new XElement("row",
new XAttribute("r", 6)),
new XElement("row",
new XAttribute("r", 7))));
Is this the best way to find the row where the r attribute is 2? This works, but I am repeating the Where clause in the select statement, and I am wondering if there is a better way and more efficent method.
int rowNumber = 2;
XElement rowElement = testElement
.Descendants("sheetData")
.Where<XElement>(item => item.Descendants("row")
.Where<XElement>(i => i.Attribute("r").Value == rowNumber.ToString())
.FirstOrDefault<XElement>() != null)
.Select<XElement, XElement>(item => item.Descendants("row")
.Where<XElement>(i => i.Attribute("r").Value == rowNumber.ToString())
.FirstOrDefault<XElement>())
.FirstOrDefault<XElement>();
In general what is the best way to determine if Linq to Xml query optimized?