Array List Question

  • Thread starter Thread starter eric
  • Start date Start date
E

eric

I have an array list with some values. I need to loop through the arraylist
and change the values. I am using the code below and I am getting an error
(like you would if i looped through a hashtable). Any ideas why?

index = 0;
foreach (object val in arrayList)
{
holeList[index] = (double)val * 2.1;
index++;
}
 
Eric,

You can not change the values in an enumeration while you are
enumerating through them. In order to do this, cycle through the elements,
like this:

for (int pintIndex = 0; pintIndex < arrayList.Count; ++pintIndex)
// Change the value.
arrayList[pintIndex] = ((double) arrayList[pintIndex]) * 2.1;

Hope this helps.
 
eric said:
I have an array list with some values. I need to loop through the arraylist
and change the values. I am using the code below and I am getting an error
(like you would if i looped through a hashtable). Any ideas why?

Yes - because you're modifying the hashtable while using an enumerator,
which you're not allowed to do. The simplest thing to do instead is:

for (int i=0; i < arrayList.Length; i++)
{
arrayList = ((double)arrayList)*2.1;
}
 
If you change a array when you are using the foreach you will get a error because that, you can put the values that you change in other arraylist and later assign the new arraylist to the old arraylist variable without trouble.


--
Bela Istok
MVP C#
Caracas, Venezuela
I have an array list with some values. I need to loop through the arraylist
and change the values. I am using the code below and I am getting an error
(like you would if i looped through a hashtable). Any ideas why?

index = 0;
foreach (object val in arrayList)
{
holeList[index] = (double)val * 2.1;
index++;
}
 
Back
Top