c# - How to handle Object reference not set to an instance of an object when using LINQ and let? -


i have following code data companies:

xdocument doc = xdocument.load(new stringreader(searchpayload)); xnamespace ns = configurationmanager.appsettings["webservicenamespace"];  var businesses = (from node in doc.descendants(ns + "searchresultsrecord")                   let abn = node.element(ns + "abn")                   let mainname = node.element(ns + "mainname")                   let legalname = node.element(ns + "legalname")                   let maintradingname = node.element(ns + "maintradingname")                   let othertradingname = node.element(ns + "othertradingname")                   let mainbusinessphysicaladdress = node.element(ns + "mainbusinessphysicaladdress")                   select new                   {                       name = new                       {                            organisationname = (string)maintradingname.element(ns + "organisationname"),                           score = (string)maintradingname.element(ns + "score"),                           iscurrentindicator = (string)maintradingname.element(ns + "iscurrentindicator"),                       },                       abn = new                       {                           identifiervalue = (string)abn.element(ns + "identifiervalue"),                           identifierstatus = (string)abn.element(ns + "identifierstatus"),                       },                       location = new                       {                           statecode = (string)mainbusinessphysicaladdress.element(ns + "statecode"),                           postcode = (string)mainbusinessphysicaladdress.element(ns + "postcode"),                           iscurrentindicator = (string)mainbusinessphysicaladdress.element(ns + "iscurrentindicator"),                       }                   }).tolist(); 

searchpayload soap message returned web service , returnes 200 searchresultrecords of of them have mainname node, legalnode, of nodes , on. if use code above error in topic because not result records have nodes how can handle this?

in name = new want available "name" nodes

thanks

i can't see in lets through, since node should non-null. , outside lets time use in blah.element(..) - have 2 choices:

  • filter out ones won't work (will remove data):

    .... let maintradingname = node.element(ns + "maintradingname") maintradingname != null .... 
  • check before using .element (will default fields blank):

    ... organisationname = maintradingname == null ? "" :       (string)maintradingname.element(ns + "organisationname"), ... 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -