This is a follow-on to another question I asked here:
https://www.codeproject.com/Answers/5162098/How-do-I-convert-this-LINQ-query-to-function-synta#answer1
I am generating the XML I require using the following code:
bool includeDetails = true;
XElement breakdown = new XElement
( "Breakdown",
new XElement( "DetailsIncluded", includeDetails ),
new XElement
( "Sections", estimateBreakdown.Sections.Select( x => new XElement
( "Section",
new XAttribute( "SectionNumber", x.SectionNumber ),
new XAttribute( "SectionName", x.SectionName ),
x.CostItems.Select( c => new XElement
( "CostItem",
new XElement( "Name", c.Name ),
new XElement( "Units", c.Units.ToString() ),
( !includeDetails ) ? null : new XElement( "UnitCost", c.UnitCost.ToString() )
))
)
))
);
return breakdown.ToString();
Which generates the following XML when
includeDetails
is true:
<Breakdown>
<DetailsIncluded>true</DetailsIncluded>
<Sections>
<Section SectionNumber="1" SectionName="Design">
<CostItem>
<Name>Site Survey</Name>
<Units>NotSpecified</Units>
<UnitCost>0</UnitCost>
</CostItem>
<CostItem>
<Name>Concept Design</Name>
<Units>NotSpecified</Units>
<UnitCost>0</UnitCost>
</CostItem>
</Section>
</Sections>
</Breakdown>
And the following XML when
includeDetails
is false:
<Breakdown>
<DetailsIncluded>false</DetailsIncluded>
<Sections>
<Section SectionNumber="1" SectionName="Design">
<CostItem>
<Name>Site Survey</Name>
<Units>NotSpecified</Units>
</CostItem>
<CostItem>
<Name>Concept Design</Name>
<Units>NotSpecified</Units>
</CostItem>
</Section>
</Sections>
</Breakdown>
All good so far. My problem is that, when
includeDetails
is true, I actually need to add two
XElement
objects to the XML. This shows what I mean, I think, however this compiles but
does not work:
( "CostItem",
new XElement( "Name", c.Name ),
new XElement( "Units", c.Units.ToString() ),
( includeDetails ) ? new XElement( "UnitCost", c.UnitCost.ToString() ) : null,
( includeDetails ) ? new XElement( "Quantity", c.Quantity.ToString() ) : null
))
Apart from the obvious inefficiency that I am testing the flag twice, I get nothing in my XML, which I suspect means I am getting an exception in the
XElement
constructor.
Can anyone show me how to do this?
What I have tried:
I am guessing that I need to generate a
List<XElement>
containing the two extra nodes that need to be added when
includeDetails
is true and then iterate over it but I can't work out the syntax.