LINQ:序列不包含任何元素错误 [英] LINQ: Sequence contains no elements error

查看:92
本文介绍了LINQ:序列不包含任何元素错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LINQ解决错误. 我正在使用LINQ拉XML节点值.我面临的问题是,当XML中不存在该节点时,出现Sequence contains no elements错误. 我尝试使用DefaultIfEmpty,Singleordefault和Firstordefault. 但是随后它引发了一个空指针异常.我想我没有正确地使用上述方法. 如何使用其中之一解决问题?

I am trying to solve an error with using LINQ. I am pulling an XML node value using LINQ. The problem I am facing is when the node is not present in the XML I'm getting Sequence contains no elements error. I tried using DefaultIfEmpty, Singleordefault, and Firstordefault. But then it throws a nullpointer exception. I guess I'm not above methods correctly. How can use one of these to solve the poblem?

这是我正在使用的LINQ代码.

Here's the LINQ code that I'm using.

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错误,而如果使用SingleOrDefault则会得到Null Reference Exception.

The OrDefault methods return the default value for the type if there is no result, which in your case would be null. That means when you do a .Element(ns + "TOTAL_COST") after that call, you'll get the Sequence contains no elements error if using Single or a Null Reference Exception if using SingleOrDefault.

您应该做的是拔出电话,并检查结果是否为空:

What you should do is pull the call out and check the result against 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;   
}

这篇关于LINQ:序列不包含任何元素错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆