Is there a way to convert IEnumerable to a collection of XElements?

I am trying to save an XML file to disk using LINQ. I have a class of business objects, including collections of strings (List), which I want to convert to XML. Is there a simple, one liner to convert this list to a list of XML elements?

For example, my list could be:

List<string> collection = new List<string>() {"1", "2", "3"} 

The output should be:

 <Collection> <Element>1</Element> <Element>2</Element> <Element>3</Element> </Collection> 

I am currently using the following syntax:

 XElement Configuration = new XElement("Configuration", new XElement("Collection", collection.ToArray() ), ); 

However, this combines the collection into one string element.

+4
source share
1 answer
 XElement Configuration = new XElement("Collection", collection.Select(c=>new XElement("Element", c))); 
+11
source

All Articles