c# - Linq 查询转换为 List<string>

标签 c# asp.net linq-to-xml type-conversion

我有这个代码

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/

相关文章:

c# - 如何使用 Linq to objects 按固定数量对我的选择进行分组?

c# - 在 C# 中解析 .eml 文件的建议

c# - 具有多个筛选器的 Azure 搜索服务

javascript - telerik 窗口不显示

asp.net - 如何通过 SSL 连接到 AD LDS?处理 "The server is not operational"错误

.net - 使用 XDocument 时如何在属性值中保留空格?

c# - 二进制转十进制

c# - 在 C# 中将 Excel XML 2003 工作表文件转换为 .XLSX 文件

c# - 在 Windows Phone 8 中解析 XML

c# - 添加 xml :space to root element