title: Foreach Iteration Null
body: <p>I am using LINQ to filter the XmlNode returned from Sharepoint WSS3's <code>listService.GetListItems()</code> method.</p>
  
  <p>This is the XML it returns:
  <a href="http://pastebin.com/mqHcserY" rel="nofollow">http://pastebin.com/mqHcserY</a></p>
  
  <p>I observed that the last row is different to the others, it does not contain the following attributes.</p>
  
  <pre><code>ows_ContentType
  ows_LinkFilenameNoMenu
  ows_LinkFilename
  ows_BaseName 
  ows__EditMenuTableStart
  </code></pre>
  
  <p>So bearing this in mind I filter the results with LINQ:</p>
  
  <pre><code>XmlNode items = listService.GetListItems(listName, string.Empty, query, viewFields, string.Empty, queryOptions, g.ToString());
  
  // Namespace for z: prefix
  XNamespace xns = "#RowsetSchema";
  
  XElement root;
  using (XmlReader xr = new XmlNodeReader(items)) { root = XElement.Load(xr); }
  
  // This query returns XElements that are Folder types
  IEnumerable&lt;XElement&gt; result = from child in root.Descendants(xns + "row")
                                 where child.Attribute("ows_ContentType").Value != null &amp;&amp; child.Attribute("ows_ContentType").Value == "Folder"
                                 select child;
  
  foreach (XElement xml in result)
  {
      //Exception when attempts to loop final XElement
  }
  </code></pre>
  
  <p>However when I iterate through the results I get a <code>NullReferenceException</code>. In a Foreach loop it will happily iterate through every object until it gets to the last one, then it will throw an exception.</p>
  
  <p>This last object is the one that differs from the other rows (I know this through process of elimination, I saw every other row get looped past) and should have been filtered out of my results as it does not have the "ows_ContentType" attribute.</p>
  
  <p>I changed my LINQ to <code>where child.Attribute("ows_ContentType").Value != null &amp;&amp; child.Attribute("ows_ContentType").Value == "Folder"</code> in attempt to filter anything that would contain a null value but I have the same results.
  I have looked at a few <a href="http://code.msdn.microsoft.com/LINQ-Restriction-Operators-b15d29ca#WhereSimple3" rel="nofollow">samples</a> and I appear to have the correct syntax.</p>
  
  <p>Could someone please explain what is causing this last XElement to return null?
  I really don't understand why it would add a null instance to the <code>&lt;IEnumerable&lt;XElement&gt; result</code> collection. </p>