有没有一种方法可以将IEnumerable转换为XElements集合?

4
我正在尝试使用LINQ将XML文件持久化到磁盘。我有一个业务对象类,其中包括字符串集合(List),我想将其转换为XML。是否有一种简单的方法来将此列表转换为XML元素列表?例如,我的列表可能是:
List<string> collection = new List<string>() {"1", "2", "3"}

输出应该是:
<Collection>
     <Element>1</Element>
     <Element>2</Element>
     <Element>3</Element>
</Collection>

目前,我正在使用以下这种语法:

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

然而,这样会将集合连接成一个单独的字符串元素。
1个回答

12
XElement Configuration = new XElement("Collection",
      collection.Select(c=>new XElement("Element", c)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接