Iteration Problem

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I am struggling trying to figure out what I am doing wrong in the following LINQ to XML code:

<pre> Dim doc As XDocument = XDocument.Load(XMLDOCUMENT)

Dim WeaponsXML = <UserAction type="Macro" id="29" iconId="0" name="Weapon 0" repeatEnabled="false" repeatCount="2" binding="Num Pad: 0
<UserAction type="UnequipItems" id="0" iconId="637" targetType="Current
<UnEquipSlot slot="1"/>
<UnEquipSlot slot="2"/>
</UserAction>
<UserAction type="Delay" id="0" iconId="623" targetType="Current" delay="1.02"/>
<UserAction type="EquipItems" id="0" iconId="625" targetType="Current
<EquipItem targetId="0"/>
</UserAction>
</UserAction>

Dim weapons = From we In doc...<Macros>.<UserAction>
Where we.@name Like "Weapon*"

MsgBox(String.Format("The file has {0} weapon arming macros.", weapons.Count))

x = weapons.Count + 1

If weapons.Count < MaxWeapons Then
For CurrentWeapon = x To MaxWeapons
WeaponsXML.@name = String.Format("Weapon {0}", CurrentWeapon)
WeaponsXML.@binding = String.Format("Num Pad: {0}", CurrentWeapon)
weapons.Last.AddAfterSelf(WeaponsXML)
MsgBox(String.Format("Current Weapon is : {0}", CurrentWeapon))
Next
End If

doc.Save(XMLDOCUMENT)
[/code]
<br/>
All works well, except that the final iteration of the for loop seems to repeat itself and actually overwrites the first element written, so I end up with two "Weapon 10" elements. One is in the position that "Weapon 6" should appear, and the other is
in the position it should be. I end up with "Weapon 10", "Weapon 7", "Weapon 8", "Weapon 9", and "Weapon 10" elements in this order. I set a breakpoint in the for loop and cant figure it out because the CurrentWeapon value appears to be correct
on each run. I even deleted the "if" but it changes nothing.
I am using VS2010 SP1 on Windows 7 Home Premium.

View the full article
 
Back
Top