LINQ:Sequence不包含任何元素错误

use*_*121 6 c# xml linq

我正在尝试使用LINQ解决错误.我正在使用LINQ提取XML节点值.我面临的问题是当XML中没有节点时我遇到Sequence contains no elements错误.我尝试使用DefaultIfEmpty,Singleordefault和Firstordefault.但是它会抛出一个nullpointer异常.我想我的方法不正确.怎样才能用其中一个来解决这个问题呢?

这是我正在使用的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;
Run Code Online (Sandbox Code Playgroud)

Dav*_*ych 7

OrDefault方法返回的默认值的类型,如果没有结果,你的情况是null.这意味着当您.Element(ns + "TOTAL_COST")在该呼叫之后执行操作时,Sequence contains no elements如果使用Single或使用Null Reference Exceptionif ,您将收到错误SingleOrDefault.

你应该做的是拉出呼叫并检查结果为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;   
}
Run Code Online (Sandbox Code Playgroud)