c# - LINQ: Sequence contains no elements errror -


i trying solve error using linq. pulling xml node value using linq. problem facing when node not present in xml i'm getting sequence contains no elements error. tried using defaultifempty, singleordefault, , firstordefault. throws nullpointer exception. guess i'm not above methods correctly. how can use 1 of these solve poblem?

here's linq code 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 default value type if there no result, in case null. means when .element(ns + "total_cost") after call, you'll sequence contains no elements error if using single or null reference exception if using singleordefault.

what should pull call out , check 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;    } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -