简体   繁体   English

如何在 XElement (XML Serializer) 内部添加 if 条件

[英]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.如何在 XElement 属性中添加条件。 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.所以我需要添加条件 if(c.Property1!=null) 得到 c.Property1 else 返回语句。 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.使用函数将需要条件的部分分解为返回“Bar”元素的辅助函数。 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.可能有一种更优雅的方法来做到这一点,但其中任何一种都可以让您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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