Re: How do you modify an array while iterating through it?
From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/17/04
- Next message: Jon Skeet [C# MVP]: "Re: Error trying to execute reflection "invoke" method"
- Previous message: Ed Courtenay: "Re: isprint"
- In reply to: Gustaf Liljegren: "Re: How do you modify an array while iterating through it?"
- Next in thread: Michael S: "Re: How do you modify an array while iterating through it?"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 17 Feb 2004 15:41:38 -0000
Gustaf Liljegren <gustaf.liljegren@bredband.net> 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.
It sounds like you should actually have two different lists (or rather,
a list and a map) - one for the input, and one for the output.
Something like (untested code)
foreach (Account account in inputList)
{
if (outputMap.ContainsKey(account.Name))
{
((Account)outputMap[account.Name]).Amount += account.Amount;
}
else
{
Account copy = new Account (account.Name, account.Amount);
outputMap[copy.Name]=copy;
}
}
-- Jon Skeet - <skeet@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too
- Next message: Jon Skeet [C# MVP]: "Re: Error trying to execute reflection "invoke" method"
- Previous message: Ed Courtenay: "Re: isprint"
- In reply to: Gustaf Liljegren: "Re: How do you modify an array while iterating through it?"
- Next in thread: Michael S: "Re: How do you modify an array while iterating through it?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|