【问题标题】:C# Lambda Method syntax to obtain attribute values that match pattern in LINQ to XML获取与 LINQ to XML 中的模式匹配的属性值的 C# Lambda 方法语法
【发布时间】:2019-02-04 23:03:41
【问题描述】:

我有以下 XML 片段,并想提取不为零的状态属性值。我可以获得符合条件的元素,但我真正想要的是状态属性的值。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
    <Auth status = "0">Moo</Auth>
    <Add status = "817">Cow</Add>
    <Add status = "888">Brown</Add>
    <Add status = "123">Dog</Add>
</response>

这个 lambda 语法会返回匹配元素的列表,但我需要的是状态值列表,而不是具有这些值的元素列表。

var errcodeList = xml.Descendants("Add").Where(x => x.Attribute("status").Value != "0").Attributes("status");

【问题讨论】:

    标签: c# xml linq lambda linq-to-xml


    【解决方案1】:

    当您使用Select 时,您将IEnumerable 投影到另一种形式中,在这种情况下,它是x.Attributes("status").Value 的列表

    var errcodeList = xml.Descendants("Add")
                         .Where(x => x.Attribute("status").Value != "0")
                         .Select(x => x.Attributes("status").Value);
    

    【讨论】:

      【解决方案2】:

      您可以使用Select 将集合投影到您想要的特定结果。例如:

      var errcodeList = xml.Descendants("Add").Where(x => x.Attribute("status").Value != "0").Select(x => x.Attribute("status").Value);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-02
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        • 2020-08-28
        • 1970-01-01
        相关资源
        最近更新 更多