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?
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;
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;
}
Use SingleOrDefault
, but then have a guard clause before trying to use costnode6
, like this:
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;
}
This will protect your LINQ query from blowing up, because the OrDefault
will make the query result null
if exactly one result is not found; and the if
condition will protect you from trying to use a null
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With