views:

85

answers:

1

Similar to this question:

http://stackoverflow.com/questions/372945/linq-iterators-selecting-and-projection

I'm wanting to use a counter or incrementing variable in a projection - however I'm wanting to use the same counter across multiple projections. I'm constructing an xml document using a number of projections based on different data sources, but need to maintain an "id" node (where the id is an incrementing value).

I can achieve this for one projection using something similar to

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

I then want to add another group of XElements to the root, continuing the counter from the previous value


Edit: Note - the above perhaps doesn't describe my issue terribly well - I'm wanting to interrogate an xml document (which was represented by the list above) and based on one set of nodes, add some new nodes to another document. Then interrogate the document for another set of nodes, and add some more new nodes to the other document, maintaining the incrementing counter across both sets.

i.e.

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))))

Ideally this would output:

 <test>
  <blah>
    <id>0</id>
  </blah>
  <blah>
    <id>1</id>
  </blah>
  <blah>
    <id>2</id>
  </blah>
  <blah>
    <id>3</id>
  </blah>
</test>
+1  A: 

The simplest is probably to concatenate your two sequences:

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

(Formatted for readability.)

Jason