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

From: Gustaf Liljegren (gustaf.liljegren_at_bredband.net)
Date: 02/17/04


Date: Tue, 17 Feb 2004 16:15:10 +0100


"Jon Skeet [C# MVP]" <skeet@pobox.com> wrote:

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

Thanks for all your help. I see that I have not given a good enough
description. It's a grouping problem. The input data is a list of accounts
(identified by name) where some accounts occurs more than once. I want the
accounts grouped so that the amounts are summed up. For example, this input
data

Account 1: 2.50
Account 2: 7.00
Account 1: 1.50
Account 3: 9.00
Account 2: 3.50
Account 2: 6.00
Account 3: 3.50
Account 1: 6.50

shall result in these groups (each in an Account object):

Account 1: 10.5
Account 2: 16.5
Account 3: 12.5

My way of doing this is looping through the input data, account by account.
If the account has already been found, I just add the amount from the
current account object. If not, I add the whole object to the array. But it
won't work, since I can't add items to the array while iterating through it.

Maybe I need an Accounts collection class with methods like AccountExists(),
AddAccount() and UpdateAmount().

Gustaf



Relevant Pages

  • Re: How do you modify an array while iterating through it?
    ... > My way of doing this is looping through the input data, account by account. ... since I can't add items to the array while iterating through it. ... It sounds like you should actually have two different lists (or rather, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: User name authenication issue
    ... > i'm assuming it's the user account... ... > It is actually saying the user account does not exist, ... >> Are you saying that the user account object does not exist or that the ... >> computer account does not exist? ...
    (microsoft.public.win2000.active_directory)
  • First shot at lisp mini-app - How to make it lispy and not lisp-c
    ... The original app is in Python with GTK as the interface. ... each account queries the TM for transactions ... global variable that each account object calls when needed, ...
    (comp.lang.lisp)
  • Re: How do you modify an array while iterating through it?
    ... See if the account already exists in the array. ... You can't change a list while you're iterating through it. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: User name authenication issue
    ... are on my domain and working under other usernames. ... It is actually saying the user account does not exist, ... > Are you saying that the user account object does not exist or that the ... > computer account does not exist? ...
    (microsoft.public.win2000.active_directory)