Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Sequence contains no elements error

Tags:

c#

xml

linq

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;
like image 654
user2574121 Avatar asked Aug 08 '13 00:08

user2574121


2 Answers

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;   
}
like image 197
Dave Zych Avatar answered Sep 18 '22 00:09

Dave Zych


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.

like image 29
Karl Anderson Avatar answered Sep 21 '22 00:09

Karl Anderson