我有这个代码
List<string> IDs = new List<string>();
XDocument doc = XDocument.Parse(xmlFile);
var query = from c in doc.Root.Elements("a").Elements("b")
select new { ID = c.Element("val").Value};
如何在没有循环 foreach 的情况下将查询转换为列表?
{ ID = c.Element("val")}
当然是字符串
编辑
我的 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<aBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<a>
<b>
<val>other data</val>
</b>
<b>
<val>other data</val>
</b>
</a>
</aBase>
最佳答案
IDs = query.Select(a => a.ID).ToList();
或者如果你想在一行中完成
List<string> IDs = (from c in doc.Root.Elements("a").Elements("b")
select c.Element("val").Value).ToList()
关于c# - Linq 查询转换为 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4998335/