Reading an empty Set with LINQ

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Given the following XML
<div style="color:Black;background-color:White; <pre>
<span style="color:Blue; <?<span style="color:#A31515; xml <span style="color:Red; version<span style="color:Blue; =<span style="color:Black; "<span style="color:Blue; 1.0<span style="color:Black; " <span style="color:Red; encoding<span style="color:Blue; =<span style="color:Black; "<span style="color:Blue; utf-8<span style="color:Black; "<span style="color:Blue; ?>
<span style="color:Blue; <<span style="color:#A31515; CompanyResult <span style="color:Red; xmlns:xsi<span style="color:Blue; =<span style="color:Black; "<span style="color:Blue; http://www.w3.org/2001/XMLSchema-instance<span style="color:Black; " <span style="color:Red; xmlns:xsd<span style="color:Blue; =<span style="color:Black; "<span style="color:Blue; http://www.w3.org/2001/XMLSchema<span style="color:Black; "<span style="color:Blue; >
<span style="color:Blue; <<span style="color:#A31515; Companies<span style="color:Blue; />
<span style="color:Blue; </<span style="color:#A31515; CompanyResult<span style="color:Blue; >
[/code]
And the following Class has been defined
<div style="color:Black;background-color:White; <pre>
[DataContract]
<span style="color:Blue; public <span style="color:Blue; class CompanyResult : BaseReturnObject
{
[DataMember]
<span style="color:Blue; public System.Collections.Generic.List<Company> Companies
{
<span style="color:Blue; get;
<span style="color:Blue; set;
}
}
[/code]
And I have the following code to convert the XML into an object
<pre> var cq = (from XElem in doc.Descendants("CompanyResult")
select new CompanyResult()
{
Companies = (from c in XElem.Descendants("Companies")
select new Company()
{
Id = c.Element("Id").Value,
RegisteredName = c.Element("RegisteredName").Value,
Number = c.Element("Number").Value
}).OfType<Company>().ToList()
}).First<CompanyResult>();[/code]
The trouble is when the code is first called the inner selection is empty and I get a null exception - namely "Object reference not set to an instance of an object." on the following code;
<pre>new Company()
{
Id = c.Element("Id").Value,
RegisteredName = c.Element("RegisteredName").Value,
Number = c.Element("Number").Value
}[/code]
This is because when starting there are no companies!
So how can I rewrite the code above and not get the Null Exception?
Thanks in advance

View the full article
 
Back
Top