Linq投影如何从select语句中检查null集合

时间:2014-10-02 15:09:02

标签: linq linq-to-xml linq-to-objects projection

我正在使用linq将对象转换为XML并遇到下面的问题(为简洁而简化):

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) 
                        ))))));

上面的代码在初始化ChildItems时工作正常并给出

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

但是,如果Childitems在作业中为空,则会抛出错误。如果为null,我想输出的是:

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

但是,我无法弄清楚如何从Select中检查null?

任何解决方案?

1 个答案:

答案 0 :(得分:1)

请尝试下面的代码,这对我来说很合适。

    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);