Note that there are some explanatory texts on larger screens.

plurals
  1. POLINQ to XML NullReferenceException AFTER returning the results?
    text
    copied!<p>I'm quite new to .NET and even more so to LINQ, which I have just begun exploring for a small project I'm working on.</p> <p>I have a XML file generated from an application that contains a few values that I want to parse into a proprietary format and save in a file.</p> <p>I'm able to make one LINQ query work fine, returning values to my Console app. Then the second query runs, also returns the requested values, but <em>then</em> throws a NRE! Why doesn't it stop iterating over the resultset after the third value has been returned?</p> <p>First, heres an excerpt of the XML file:</p> <pre><code>&lt;analyse&gt; &lt;sample&gt;Leer 12&lt;/sample&gt; sample ID and number &lt;id&gt;Leer&lt;/id&gt; sample ID &lt;/analyse&gt; &lt;results&gt; &lt;element&gt; &lt;name&gt;c&lt;/name&gt; &lt;value&gt;0.000186156337031958&lt;/value&gt; &lt;/element&gt; &lt;element&gt; &lt;name&gt;co2&lt;/name&gt; &lt;value&gt;0.000682099902270885&lt;/value&gt; &lt;/element&gt; &lt;element&gt; &lt;name&gt;s&lt;/name&gt; &lt;value&gt;0.000121750914950204&lt;/value&gt; &lt;/element&gt; &lt;element&gt; &lt;name&gt;so3&lt;/name&gt; &lt;value&gt;0.000304028592755094&lt;/value&gt; &lt;/element&gt; &lt;/results&gt; </code></pre> <p>This is the first LINQ query:</p> <pre><code>XDocument uniSample = XDocument.Load(limsfile); var analyse = uniSample.Descendants("analyse").Select(el =&gt; new { Sample = el.Element("sample").Value, Id = el.Element("id").Value }); foreach (var el in analyse) { Console.WriteLine("Sample: " + el.Sample); Console.WriteLine("Sample ID: " + el.Id); } </code></pre> <p>This is the second LINQ query: (note how I had to rename the anonynous type Value because it seemed to conflict with something) </p> <pre><code>var results = uniSample.Descendants("element").Select(elements =&gt; new { Name = elements.Element("name").Value, Verdi = elements.Element("value").Value }); foreach (var el in results) { Console.WriteLine("Name: " + el.Name); Console.WriteLine("Value: " + el.Verdi); } </code></pre> <p>Now the output from the program looks like what you'd expect</p> <pre><code>Sample: Leer 12 Sample ID: Leer Name: c Value: 0.000186156337031958 Name: co2 Value: 0.000682099902270885 Name: s Value: 0.000121750914950204 Name: so3 Value: 0.000304028592755094 </code></pre> <p>...but then after the third iteration, the NRE is thrown, pointing at the latter LINQ query. Why isn't it exiting the foreach loop like it does the first time??</p> <p>Edit: Actually it's after the FOURTH iteration, sorry for the mixup! :) Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload