简体   繁体   中英

How to add if condition in inside XElement (XML Serializer)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM