score:1

Accepted answer

You can just pass in null if the property is null:

var xml = new XElement("LabPostResult", labPostResultList.Select(x => new XElement("row",
                   new XAttribute("PatientID", x.PatientID),
                   x.AnalyteName != null ? new XAttribute("AnalyteName", x.AnalyteName) : null,
                   new XAttribute("TestName", x.Loinc)      
                                       )));

This way the attribute won't be created for objects which don't have AnalyteName.

score:1

You can write an extension method. It will much cleaner.

    public static XElement ToXElement(this string content, XName name)
    {
        return content == null ? null : new XElement(name, content);
    }

And call it as below.

public static void StoreResult(List<LabPostResult> labPostResultList)
    {
        var xml = new XElement("LabPostResult", 
                                labPostResultList.Select(x => new XElement("row",
                                         new XAttribute("PatientID", x.PatientID),
                                         x.AnalyteName.ToXElement("AnalyteName"),
                                         x.Loinc.ToXElement("TestName")
                                               )));
    }

Related Articles