[RESOLVED] LINQ null return issue
I'm having trouble figuring out what to do with the bolded part, when there are no nodes to return.
If there are no image tags inside the <images> tag, i get an "Object reference is not set to an instance of an object".
I have been searching and searching for an answer but can't find one.
Code:
Dim orders = From o In xmlLinq.Descendants("order")
Select New With { _
.orderID = o.Attribute("id").Value, _
.userID = o.Element("user").Element("userid").Value, _
.firstname = o.Element("user").Element("firstname").Value, _
.lastname = o.Element("user").Element("lastname").Value, _
.username = o.Element("user").Element("username").Value, _
.password = o.Element("user").Element("password").Value, _
.address_1 = o.Element("user").Element("address_1").Value, _
.address_2 = o.Element("user").Element("address_2").Value, _
.city = o.Element("user").Element("city").Value, _
.state = o.Element("user").Element("state").Value, _
.postal = o.Element("user").Element("postal").Value, _
.email = o.Element("user").Element("email").Value, _
.phone = o.Element("user").Element("phone").Value, _
Key .ads = From a In o.Descendants("ad")
Where a.Attribute("type").Value = "Web"
Select New With { _
.type = a.Attribute("type").Value, _
.headline = a.Element("text").Element("headline").Value, _
.body = a.Element("text").Element("body").Value, _
.run_length = a.Element("regions").Element("region").Element("schedule").Attribute("run_length").Value, _
.start_date = a.Element("regions").Element("region").Element("schedule").Attribute("start_date").Value, _
Key .images = From i In a.Descendants("images")
Select New With { _
.image = i.Element("image").Value _
}
}
}
Re: LINQ null return issue
Something like:
vb.net Code:
.image = If(i.Element("image") Is Nothing, CObj(Nothing), i.Element("image").Value)
The CObj may or may not work. If not then you'll have to cast the null reference as the appropriate type.
Re: LINQ null return issue
Cool, thanks...that worked perfect. I had thought about an If, but I wasn't sure what would go in the TRUE portion of it.