Question

Essentially I have a loop that should remove gold from all the backpacks and add back a different amount and it throws a collection was modified error, apparently the way it worked was completely different in .NET 2.0, could anyone give me a hand?

Type[] types = new Type[] { typeof( Gold ) };

int[] amounts = new int[] { 1 };

foreach( Item i8 in World.Items.Values )
{
    if( i8 is Container ) 
    { 
        Container c1 = (Container)i8; 
        int _Index = BackpackList.IndexOf(c1.Serial);
        if ( _Index>=0 )
        {
            amounts[0] = GoldOriginal[_Index];
            int NewAmount = GoldAmounts[_Index];

            if (c1!=null) { c1.ConsumeTotal( types, amounts ); }
            if (c1!=null && NewAmount>0) { c1.AddItem(new Gold(NewAmount)); }
        }
    }
}
Was it helpful?

Solution

Type[] types = new Type[] { typeof( Gold ) };

int[] amounts = new int[] { 1 };

List<Item> items = new List<Item>(World.Items.Values);
foreach( Item i8 in items  )
{
    if( i8 is Container ) 
    { 
        Container c1 = (Container)i8; 
        int _Index = BackpackList.IndexOf(c1.Serial);
        if ( _Index>=0 )
        {
            amounts[0] = GoldOriginal[_Index];
            int NewAmount = GoldAmounts[_Index];

            if (c1!=null) { c1.ConsumeTotal( types, amounts ); }
            if (c1!=null && NewAmount>0) { c1.AddItem(new Gold(NewAmount)); }
        }
    }
}

This change will prevent the error. The change will ignore additions or deletions to World.Items while you are iterating over it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top