LINQ:Sequence不包含任何元素错误
我试图使用LINQ解决错误。 我正在使用LINQ提取XML节点值。 我面临的问题是当XML Sequence contains no elements
节点时我得到的Sequence contains no elements
错误。 我尝试使用DefaultIfEmpty,Singleordefault和Firstordefault。 但是它会抛出一个nullpointerexception。 我想我的方法不正确。 怎样才能用其中一个来解决这个问题呢?
这是我正在使用的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
将为null
。 这意味着当你在该调用之后执行.Element(ns + "TOTAL_COST")
,如果使用SingleOrDefault
如果使用Single
或Null Reference Exception
,则会得到Sequence contains no elements
错误。
你应该做的是拉出呼叫并检查结果为null:
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; }
使用SingleOrDefault
,但在尝试使用costnode6
之前有一个guard子句,如下所示:
var costnode6 = doc.Root.Descendants(ns + "SERVICEUPGRADES").SingleOrDefault(c => (string)c.Element(ns + "DELIVERYTIME") == "before 3:30 PM").Element(ns + "TOTAL_COST"); if(costnode6 != null) { var cost6 = (decimal)costnode6; }
这将保护您的LINQ查询免于OrDefault
,因为如果没有找到一个结果, OrDefault
将使查询结果为null
; if
条件将保护您不要尝试使用null
对象。