我正在尝试使用 LINQ 解决错误。
我正在使用 LINQ 提取 XML 节点值。我面临的问题是,当节点不存在于 XML 中时,我收到了 Sequence contains no elements
错误。
我尝试使用 DefaultIfEmpty、Singleordefault 和 Firstordefault。
但随后它抛出空指针异常。我想我没有正确地超越方法。
如何使用其中之一来解决问题?
这是我正在使用的 LINQ 代码。
var costnode6 = doc.Root.Descendants(ns + "SERVICEUPGRADES").Single(c => (string)c.Element(ns + "DELIVERYTIME") == "before 3:30 PM").Element(ns + "TOTAL_COST");
var cost6 = (decimal)costnode6;
最佳答案
如果没有结果,OrDefault
方法返回类型的默认值,在您的情况下为 null
。这意味着当您在该调用之后执行 .Element(ns + "TOTAL_COST")
时,如果使用 Single<,您将得到
或 Sequence contains no elements
错误Null Reference Exception
(如果使用 SingleOrDefault
)。
你应该做的是拉出调用并检查结果是否为空:
var deliveryTime = doc.Root.Descendants(ns + "SERVICEUPGRADES")
.SingleOrDefault(c => (string)c.Element(ns + "DELIVERYTIME") == "before 3:30 PM");
if(deliveryTime != null)
{
var costnode6 = deliveryTime.Element(ns + "TOTAL_COST");
var cost6 = (decimal)costnode6;
}
关于c# - LINQ:序列不包含任何元素错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18115926/