How to conditionally add new XElement into an existing root element in wpf?
c#, wpf
Solution
You can use a so-called `ternary operator` for this:
condition ? 'value if true' : 'value if false';
or, in your case:
...
new XAttribute("Type", "default type"),
status ? new XElement("Content", getContent()) : null,
new XElement("Width", 120),
...
Problem
I created an `XElement` by this way: ``` private void Analyze( IEnumerable<XElement> inputData) { XElement rootElement = new XElement("Items", from singleInputItem in inputData select new XElement("Element", new XAttribute("ID", "default ID"), new XAttribute("Type", "default type"), new XElement("Width", 120), new XElement("Height",150) )); } ``` Also I created a simple function like this: ``` private int contentNumber = 0; private void getContent() { return contentNumber++; } private bool status = false; //some function to change status here ``` Now I want to add a new `XElement` into `rootElement` within `Element` when `status` is `true`, so I want to do something like this: ``` private void Analyze( IEnumerable<XElement> inputData) { XElement rootElement = new XElement("Items", from singleInputItem in inputData select new XElement("Element", new XAttribute("ID", "default ID"), new XAttribute("Type", "default type"), if( status == true ) { new XElement("Content", getContent()); } new XElement("Width", 120), new XElement("Height",150) )); } ``` Obviously, the above `if` part isn't correct. But I couldn't find any solution to do the same thing on the internet. Could someone help? Thanks.