Search code examples
linqlinq-to-xmllinq-to-objectsprojection

Linq projection how to check for null collection from select statement


I am converting an object to XML using linq and got stuck with a problem below (simplified for brevity):

public class Job
{
    public string JobNumber{ get; set; }
    public string ClientType { get; set; }
    public List<ChildItem> ChildItems { get; set; }
}

public class ChildItem
{
    public string Id{ get; set; }
}

 var data = DAL.GetJobs();
            var xml = new XElement("records",
                data.Select(i => new XElement("record",
                    new XAttribute("JobNumber", i.JobNumber),                       
                    new XAttribute("ClientType", i.ClientType),                        
                          new XElement("Items",
                                i.ChildItems.Select(j=>new XElement("Item",
                                new XAttribute("ID", j.Id) 
                        ))))));

The above code works fine when ChildItems is initialised and gives

<records>
  <record JobNumber="12" ClientType="ABC">
   <Items>
     <Item ID="1"/>
     <Item ID="2"/>
   </Items>
  </record>
</records>

However, when the Childitems is null in job it throws an error. In case of null all I want to output is:

<records>
 <record JobNumber="12" ClientType="ABC">
  <Items>        
  </Items>
 </record>
</records>

However, I am not able to figure out how to check for null from within the Select?

Any solutions?


Solution

  • Please try the below code, which working fine for me.

        var data = new List<Job> { new Job { JobNumber = "12", ClientType = "ABC" } };
    
            var xml = new XElement("records",
                data.Select(i => new XElement("record",
                    new XAttribute("JobNumber", i.JobNumber),
                    new XAttribute("ClientType", i.ClientType), 
                          new XElement("Items",
                                (i.ChildItems ?? new List<ChildItem>()).Select(j => new XElement("Item",
                                new XAttribute("ID", j.Id)
                        ))))));
    
            Console.WriteLine(xml.CreateNavigator().OuterXml);