Q:

 to XML with Linq c#

I've already parsed a horrible document into a list, but I'm having issues formatting it with Linq and cant seem to get it quite right.
My code looks like this:
var xEle = new XElement("WorkOrder",
           from item in items 
           select new XElement(item.SECTION,
                      new XElement(item.DATANAME, item.DATAVALUE)));

Which produces something like this:
      <WorkOrder>
      <JOBDETAILS>
        <JOBNUMBER>12345</JOBNUMBER>
      </JOBDETAILS>
      <JOBDETAILS>
        <ACTIVITYNO>/01</ACTIVITYNO>
      </JOBDETAILS>
      <JOBDETAILS>
        <JOBCCD>15/06/2015
    </JOBCCD>
      </JOBDETAILS>
      <JOBDETAILS>
        <REQUIRED>15/06/2016
    </REQUIRED>
      </JOBDETAILS>
      <COMPANYDETAILS>
        <COMPANY>Adventure Works
    </COMPANY>
      </COMPANYDETAILS>
      <COMPANYDETAILS>
        <STREET>LTD
    </STREET>
      </COMPANYDETAILS>
      <COMPANYDETAILS>
        <LOCALITY>123 Street
    </LOCALITY>
      </COMPANYDETAILS>
      <COMPANYDETAILS>
        <TOWN>Local Town
    </TOWN>
      </COMPANYDETAILS>
      <COMPANYDETAILS>
        <COUNTY>County Name
    </COUNTY>
      </COMPANYDETAILS>
      <COMPANYDETAILS>
        <POSTCODE>ABC 1234
    </POSTCODE>
<COMMENTS>
    <COMMENT>this is a comment</COMMENT>
</COMMENTS>
</WorkOrder>

I'm trying to get it to be grouped by my item.SECTION (in the example output this would be JOBDETAILS & COMPANYDETAILS) which I want to produce something like this:
<WorkOrder>
   <JOBDETAILS>
         <JOBNUMBER>12345</JOBNUNMBER>
         <ACTIVITYNO>/01</ACTIVITYNO>
         <JOBCCD>15/06/2015</JOBCCD>
         <REQUIRED>15/06/2016</REQUIRED>
   </JOBDETAILS>
   <COMPANYDETAILS>
         <COMPANY>Adventure Works</COMPANY>
         <STREET>LTD</STREET>
         <LOCALITY>123</LOCALITY>
   </COMPANYDETAILS>
   <COMMENTS>
         <COMMENT>THIS IS A COMMENT</COMMENT>
   </COMMENTS>
</WorkOrder>

My list is dynamic and does not contain a specific set of fields each time, hence why I have not hard coded the output.
I dont think I'm a million miles away, and would appreciate a kick in the right direction.

A:

You need to add a groupby to group the results by the section.
var xEle =
    new XElement("WorkOrder",
       from item in items 
       group item by item.SECTION into g
       select new XElement(g.Key,
                  g.Select(i => new XElement(i.DATANAME, i.DATAVALUE))));

Note that you also need two selects, one to build up the list of elements and another to wrap them together. (Note that I used function syntax by you could also say a variant of from i in g select)

