tags:

views:

27

answers:

1

I have a list of strings that I need to use to create the following XML. The items in the list are strings "Line 1", "Line 2" etc. The tricky bit is that the element names increment from "l1" upwards. Is it possible to use Linq to do this or should I use a different approach ?

<srv>
  <enqRsp>
    <l1>LINE 1</l1>
    <l2>LINE 2</l2>
    <l3>LINE 3</l3>
    <l4>LINE 3</l4>
  </enqRsp>
</srv>
+2  A: 

This is totally possible, using the Select overload which provides the index as well as the value:

var document = new XDocument(new XElement("srv",
     new XElement("enqRsp",
        list.Select((value, index) => new XElement("l" + (index+1), value))
     )
));
Jon Skeet
That works great, thanks.
Retrocoder