Peter Green
Peter Green

Reputation: 99

Linq to XML - Create Xelement only IF something

I'm new to linq to xml and trying to do the following. I'm creating a new xml, from some objects i receive.

I have a XElement called "Scale" There is a Bool Value "DynamicScale", in case it is False, I need to create two XElements as descendants of Scale, if it is True, i don't need these elements.

  <Scale DynamicScale="False">
    <LowScale>0</LowScale>
    <HighScale>10000</HighScale>
  </Scale>

Is there any way to add an If statement in the middle of the creation of this? Or any other suggestions to deal with this need? This if what I'd like to be able to do (I know it's not possible like this). Any simple way is welcome.

new XElement("Scale",
    new XAttribute("DynamicScale", c.DynamicScale),
    if (c.DynamicScale == false)
    {
        new XElement("LowScale", c.LowScale),
        new XElement("HighScale", c.HighScale),
    })

Upvotes: 2

Views: 296

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

new XElement("Scale",
     new XAttribute("DynamicScale",  c.DynamicScale),
     c.DynamicScale ? null : new XElement("LowScale", c.LowScale),
     c.DynamicScale ? null : new XElement("HighScale", c.HighScale));

For non dynamic scale this will produce

  <Scale DynamicScale="False">
    <LowScale>0</LowScale>
    <HighScale>10000</HighScale>
  </Scale>

For dynamic scale

  <Scale DynamicScale="True"/>

Or shorter version:

new XElement("Scale",
     new XAttribute("DynamicScale",  c.DynamicScale),
     c.DynamicScale ? null : new XElement[] {
                  new XElement("LowScale", c.LowScale),
                  new XElement("HighScale", c.HighScale) }
     );

Upvotes: 3

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60503

Use the ternary operator

new XElement(
    "Scale",
    new XAttribute("DynamicScale", c.DynamicScale), 
    c.DynamicScale ? 
        null: 
        new[]
        { 
            new XElement("HighScale", c.HighScale),
            new XElement("LowScale", c.LowScale)
        }
);

Upvotes: 5

Related Questions