【问题标题】:"Value cannot be null" while creating an XElement from the attributes where one or more value is null从一个或多个值为空的属性创建 XElement 时“值不能为空”
【发布时间】:2017-05-19 10:15:05
【问题描述】:

我正在尝试以下代码:

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”字段中存在值时,这可以正常工作。但是,如果这三个中的任何一个为空,那么我会收到一条错误消息 - “值不能为空”。

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

但是有没有优化或更有效的方法来解决这个问题?

感谢和问候,

尼尔曼

【问题讨论】:

  • 如果要保留属性为空值i.Response?.NotificationProvider ?? string.Empty
  • 您想如何标记没有Response 的通知的PIDUID
  • @LeonidVasilyev - 我只想忽略这些属性,以防 Response 为空,或者它们各自的属性为空/空。

标签: c# .net xml linq linq-to-xml


【解决方案1】:

你可以只用一次空检查(而且你不需要封闭对象[]):

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

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多