0
var xmlfromLINQ = new XElement("BarList",
            from c in BarList 
            select new XElement("Bar",
                new XElement("Property1", c.Property1),
                new XElement("Property2", c.Property2)
             ));

How To add a condition in inside a XElement property. Because some property is null, if my my property is i get error. so i need add condition if(c.Property1!=null) get the c.Property1 else return the statement. How to add it.

CoderGreat
  • 11
  • 2
  • If you are using a schema and the schema is requiring the parameter, than the XML input a bad an needs to be fixed. Modifying the c# code is just a Kludge and should only be used temporarily. I would just modify the xml temporarily until I get a good xml file from my suppliers. If a permanent fix is required I usually just make the object accept a null like for integers make the property int? – jdweng Nov 08 '20 at 14:35

1 Answers1

0

There are two ways I would try:

  1. Don't nest it If you are struggeling, it is usually a good practice to create all the elements in a separate line and assign them to a variable. In the end you assemble your structure using the variables you created. This might not be pretty and it is not considered elegant, but it is readable and easy to debug. So whenever I start with something new, I use that method until I really understand what is going on. Making it pretty and shortening it is the second step.

  2. Use a function Break out the part that requires the conditions into a helper function that returns the "Bar" element. You can add the check for the property and then decide how to assemble the object.

There is probably a more elegant way to do this, but either of those will allow you to solve the problem.