title: How to build an XDocument with a foreach and LINQ?
body: <p>I can use XDocument to build the following file which <strong>works fine</strong>:</p>
  
  <pre><code>XDocument xdoc = new XDocument
  (
      new XDeclaration("1.0", "utf-8", null),
      new XElement(_pluralCamelNotation,
          new XElement(_singularCamelNotation,
              new XElement("id", "1"),
              new XElement("whenCreated", "2008-12-31")
          ),
          new XElement(_singularCamelNotation,
              new XElement("id", "2"),
              new XElement("whenCreated", "2008-12-31")
              )
          )
  );
  </code></pre>
  
  <p><strong>However</strong>, I need to build the XML file by <strong>iterating through a collection</strong> like this:</p>
  
  <pre><code>XDocument xdoc = new XDocument
  (
      new XDeclaration("1.0", "utf-8", null));
  
  foreach (DataType dataType in _dataTypes)
  {
      XElement xelement = new XElement(_pluralCamelNotation,
          new XElement(_singularCamelNotation,
          new XElement("id", "1"),
          new XElement("whenCreated", "2008-12-31")
      ));
      xdoc.AddInterally(xelement); //PSEUDO-CODE
  }
  </code></pre>
  
  <p>There is <strong>Add</strong>, <strong>AddFirst</strong>, <strong>AddAfterSelf</strong>, <strong>AddBeforeSelf</strong>, but I could get none of them to work in this context. </p>
  
  <p><strong>Is an iteration with LINQ like this possible?</strong></p>
  
  <h1>Answer:</h1>
  
  <p>I took Jimmy's code suggestion with the root tag, changed it up a bit and it was exactly what I was looking for:</p>
  
  <pre><code>var xdoc = new XDocument(
      new XDeclaration("1.0", "utf-8", null),
      new XElement(_pluralCamelNotation,
          _dataTypes.Select(datatype =&gt; new XElement(_singularCamelNotation,
              new XElement("id", "1"),
              new XElement("whenCreated", "2008-12-31")
          ))
      )
  );
  </code></pre>
  
  <p>Marc Gravell posted a better answer to this <a href="https://stackoverflow.com/questions/1032314/how-can-i-change-this-stringbuilder-to-xml-code-to-linq-to-xml/1032363#1032363">on this StackOverflow question</a>.</p>