【问题标题】:How can I search for siblings using linq?如何使用 linq 搜索兄弟姐妹?
【发布时间】:2012-09-24 15:43:30
【问题描述】:

鉴于以下 XML(Excel XML 数据表中的两行),我想查找所有 Cost 值并找到相关的 AltID

...
   <Row ss:AutoFitHeight="0">
    <Cell ss:StyleID="s62"><Data ss:Type="String" AltID="1" ColumnHeader="AltName">Alternative 2</Data></Cell>
    <Cell ss:StyleID="s62"><Data ss:Type="Number" ColumnHeader="Total">0.105468638</Data></Cell>
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Cost">123</Data></Cell>
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Risk">456</Data></Cell>
   </Row>
   <Row ss:AutoFitHeight="0">
    <Cell ss:StyleID="s62"><Data ss:Type="String" AltID="2" ColumnHeader="AltName">Alternative 3</Data></Cell>
    <Cell ss:StyleID="s62"><Data ss:Type="Number" ColumnHeader="Total">1.7803949999999999</Data></Cell>
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Cost">123</Data></Cell>
    <Cell ss:StyleID="s64"><Data ss:Type="Number" ColumnHeader="Risk">456</Data></Cell>
   </Row>
...

我可以很容易地找到成本,但我需要找到一种方法,在给定成本的情况下,“上”一级到 ,然后找到 所在的单元格ColumnHeader 等于 AltName,然后给我 AltID 属性。

    Dim costs = From item In dg...<Table>...<Row>...<Cell>...<Data> Select item Where item.@ColumnHeader = "Cost"
    For Each i In costs
        dim CostValue as Integer = i.value
        dim AltID as Integer = ...
    Next

【问题讨论】:

  • 为什么要使用linq?为什么不使用简单的 XPath 查询?

标签: asp.net vb.net linq


【解决方案1】:

您无需使用三个点来浏览每个元素。 Triple dot 是 .Descendents 的简写。您可以将其简化为 dg... 只要您不关心 Data 节点在层次结构中的位置。获得所需节点后,您可以使用 Parent 向上导航图表,然后根据需要再次向下导航。这应该为您提供给定节点的 AltID 属性:

 Dim costs = From item In dg...<Data> 
    Where item.@ColumnHeader = "Cost"
    select item.Parent.Parent...<Data>.
               FirstOrDefault(Function(node) node.Attribute("ColumnHeader").Value = "AltName").@AltID

或者,您可以使用 Ancestors 而不是 .Parent.Parent 来实现相同的目标。见http://www.dbtalks.com/uploadfile/a7e1c8/linq-to-xml-axis-methods-part-1-ancestors-and-ancestorsands/

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 2019-08-29
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    相关资源
    最近更新 更多