1

この質問に似ています:

LINQ、イテレータ、選択と射影

プロジェクションでカウンターまたはインクリメント変数を使用したいのですが、複数のプロジェクションで同じカウンターを使用したいと思っています。さまざまなデータソースに基づく多数のプロジェクションを使用してxmlドキュメントを作成していますが、「id」ノード(idは増分値)を維持する必要があります。

私はこれを1つの投影で次のようなものを使用して達成できます

Dim x as New XElement("rootNode", list.Select(Of XElement)(Function(xe, count) new XElement("blah", count+1)))

次に、XElementsの別のグループをルートに追加し、前の値からカウンターを続けます。


編集:注-上記はおそらく私の問題をひどくうまく説明していません-xmlドキュメント(上記のリストで表されています)に問い合わせて、ノードの1つのセットに基づいて、別のドキュメントにいくつかの新しいノードを追加したいと思います。次に、ドキュメントに別のノードセットを問い合わせ、新しいノードを別のドキュメントに追加して、両方のセットで増分カウンターを維持します。

すなわち

Dim orig = <root>
                       <itemtype1>
                           <item>
                               <name>test</name>
                               <age>12</age>
                           </item>
                           <item>
                               <name>test2</name>
                               <age>13</age>
                           </item>
                       </itemtype1>
                       <itemtype2>
                           <item>
                               <name>testing</name>
                               <age>15</age>
                           </item>
                           <item>
                               <name>testing</name>
                               <age>14</age>
                           </item>
                       </itemtype2>
                   </root>

    Dim newX As New XElement("test", orig.Descendants("itemtype1"). _
                             Descendants("item").Select(Of XElement)(Function(xe, count) New XElement("blah", New XElement("id", count))), _
                                                        orig.Descendants("itemtype2"). _
                             Descendants("item").Select(Of XElement)(Function(xe, count) New XElement("blah", New XElement("id", count))))

理想的には、これは次のように出力されます。

 <test>
  <blah>
    <id>0</id>
  </blah>
  <blah>
    <id>1</id>
  </blah>
  <blah>
    <id>2</id>
  </blah>
  <blah>
    <id>3</id>
  </blah>
</test>
4

1 に答える 1

1

最も簡単なのは、おそらく2 つのシーケンスを連結することです。

Dim x as New XElement("rootNode", list.Concat(list2) _
                                      .Select(Of XElement)(Function(xe, count) _
                                          New XElement(xe, count + 1)) _
                     )

(読みやすいようにフォーマットされています。)

于 2010-02-09T03:27:09.733 に答える