"Value cannot be null" 从一个或多个值为 null 的属性创建 XElement 时

"Value cannot be null" while creating an XElement from the attributes where one or more value is null

我正在尝试以下代码:

XElement element = new XElement("ENTS", from i in notificationsTracking
select new XElement("ENT", 
new object[] {
    new XAttribute("ENTID", i.TrackingID),
    new XAttribute("PID", i.Response?.NotificationProvider),
    new XAttribute("UID", i.Response?.NotificationUniqueId)
}));

当响应不为 null 且 "NotificationProvider" 或 "NotificationUniqueId" 字段中存在值时,此方法工作正常。但是如果这三个中的任何一个为空,那么我会收到一条错误消息 - "Value cannot be null".

我知道有一种解决方案,其中我可以明确地将对象/属性与 Null/Empty 进行比较,并可以相应地转换它们,这将起作用。

但是有什么优化或更有效的方法可以解决这个问题吗?

感谢和问候,

尼尔曼

您只需进行一次空检查即可完成此操作(并且不需要封闭对象[]):

XElement element = new XElement("ENTS", from i in notificationsTracking
select new XElement("ENT", 
    new XAttribute("ENTID", i.TrackingID),
    i.Response != null ? new [] {
        new XAttribute("PID", i.Response.NotificationProvider),
        new XAttribute("UID", i.Response.NotificationUniqueId),
        // more i.Response props ...
    } : null
));

或者如果只有两个简单地重复检查:

XElement element = new XElement("ENTS", from i in notificationsTracking
select new XElement("ENT", 
    new XAttribute("ENTID", i.TrackingID),
    i.Response != null ? new XAttribute("PID", i.Response.NotificationProvider) : null,
    i.Response != null ? new XAttribute("UID", i.Response.NotificationUniqueId) : null
));