Re: How do you modify an array while iterating through it?

Tech-Archive recommends: Fix windows errors by optimizing your registry

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/17/04


Date: Tue, 17 Feb 2004 13:37:46 -0000

Gustaf Liljegren <gustaf.liljegren@bredband.net> wrote:

<snip>

> So, the problem remaining is how to add another Account within that loop.
> The logic is:
>
> 1. See if the account already exists in the array.
> 2. If it does, add a new amount to the old one. If not, create a new account
> in the array.
>
> I'll see if I can come up with a simple example to work on.

You can't change a list while you're iterating through it. One common
solution is to build up another list containing the items you *want* to
add to the list, and then add all of them after you've finished
iterating. (You could use ArrayList.AddRange for that.)

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • Re: missing values from files
    ... This will loop 14 times, ... If you want to loop over an array use the ... If you want to loop over a range you still should use the iterating ...
    (perl.beginners)
  • Re: missing values from files
    ... This will loop 14 times, ... If you want to loop over an array use the ... If you want to loop over a range you still should use the iterating ...
    (perl.beginners)
  • Re: Readline using foreach and while
    ...     print; ... before iterating begins - therefore the values of the new list are ... If there is only a single array, ... consistant if you really think about it. ...
    (comp.lang.perl.misc)
  • Re: Efficient processing of large nuumeric data file
    ... to see how much time is consumed merely by iterating over the ... try/except blocks, mapor int() calls. ... an upper bound on the data, so it seems to me that some kind of array ... I'm not sure an array would net you great savings here, ...
    (comp.lang.python)
  • Data Load Query
    ... it into a MS SQL database. ... array that can vary between 1 to 50. ... Account Number ... which has a link to the customer information file. ...
    (comp.databases.ms-sqlserver)