我想从对象列表中创建一个XML文档。如何在变换中处理Null。
XElement xml = new XElement("people",
from p in PPL
select new XElement("person",
new XElement("id", p.ID),
new XElement("firstname", p.FirstName),
new XElement("lastname", p.LastName),
new XElement("idrole", p.IDRole)));
如上例所示,如果 PPL 为null,那么我的xml应该只有< \ people>现在我收到了NUllreferenc错误。
提前致谢 BB
答案 0 :(得分:4)
一种选择是使用空合并运算符:
from p in PPL ?? Enumerable.Empty<Person>()
如果您需要为匿名类型的集合执行此操作,则可以创建扩展方法:
public static IEnumerable<TSource> EmptyIfNull<TSource>
(this IEnumerable<TSource> source)
{
return source ?? Enumerable.Empty<TSource>();
}
然后您的查询可以使用
from p in PPL.EmptyIfNull()