473,583 Members | 3,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I have a bug in foreach loop

Error:
Collection was modified; enumeration operation may not execute.

I've dodged this issue for a while now with workarounds but now i want to
stand up and fight.
I don't want to run away from it anymore.
How do I get around tampering with a collection within a loop and keep
iterating. Here is my code:

//Threadwork.Getl ist returns a hash table
foreach(Diction aryEntry key in ThreadWork.GetL ist)
{
lock(ThreadWork .GetList)
ThreadWork.GetL ist.Remove(key. Key.ToString()) ;
}

I know why it is happening, but I don't know how to fix it. I've had the
same issue with operations like this
foreach(listite m li in somelistbox.ite ms)
{
trying to remove 2 li items in succession will throw the same exception
because the collection is modified.
}

I know how to work around it by using an arraylist as a temporary container
but I don't want a work around anymore. I want to fix it. I want to remove
the item and keep iterating without using a secondary container to store the
values. I think that workaround is ineligant, cheap and doesn't promote
robust coding. Yuck!

I'd like some help please.
--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
Nov 15 '05 #1
7 4374
You can use for loops instead
for(int x = 0; x < list.Count; x++)
{
object o = list[x];
// if o should be removed
{
list.Remove(o);
x--; // to check the same x again since this spot will be filled by
"x+1" and so on
}
}

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #2
Morten Wennevik <Mo************ @hotmail.com> wrote:
You can use for loops instead
for(int x = 0; x < list.Count; x++)
{
object o = list[x];
// if o should be removed
{
list.Remove(o);
x--; // to check the same x again since this spot will be filled by
"x+1" and so on
}
}


Another alternative is to iterate from the other end:

for (int x=list.Count-1; x >=0 ; x--)
{
object o = list[x];
// if o should be removed
{
list.RemoveAt(x );
}
}

Note that I've changed list.Remove(o) to list.RemoveAt(x ) as that way
the list doesn't need to search for the object to remove and it means
that the *exact* element will be removed rather than one which is equal
and potentially earlier in the list.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #3
So I guess there is no way to iterate thru a collection and tamper with it
then?
I'm not complaining but it seems like if they can implement edit and
continue, they could have implemented this.

I know this solution, I've used it but I was kinda hoping, praying that the
foreach version was available somehow.

Thanks anyway

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"Morten Wennevik" <Mo************ @hotmail.com> wrote in message
news:oprxwa3fpg hntkfz@localhos t...
You can use for loops instead
for(int x = 0; x < list.Count; x++)
{
object o = list[x];
// if o should be removed
{
list.Remove(o);
x--; // to check the same x again since this spot will be filled by
"x+1" and so on
}
}

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 15 '05 #4
yes, but that is really only a work around. There seems to be no way to edit
the collection while iterating thru it since it is read only. We had that
ability in C++ by the way. I'm not starting a new thread here. just saying
that i'll stash that quirk away in the archives of .net faux pas.

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Morten Wennevik <Mo************ @hotmail.com> wrote:
You can use for loops instead
for(int x = 0; x < list.Count; x++)
{
object o = list[x];
// if o should be removed
{
list.Remove(o);
x--; // to check the same x again since this spot will be filled by
"x+1" and so on
}
}


Another alternative is to iterate from the other end:

for (int x=list.Count-1; x >=0 ; x--)
{
object o = list[x];
// if o should be removed
{
list.RemoveAt(x );
}
}

Note that I've changed list.Remove(o) to list.RemoveAt(x ) as that way
the list doesn't need to search for the object to remove and it means
that the *exact* element will be removed rather than one which is equal
and potentially earlier in the list.

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

Nov 15 '05 #5
I think I lost something converting the foreach to a for loop. I can no
longer correctly obtain the hash code key thru casting. It's bugging me out.

The previous code
foreach(Diction aryEntry key in ThreadWork.GetL ist) retrieved a hashtable.
The foreach automatically

presented me with the index key for that hashtable. Each key is an index for
an array object of length 19. So i could do this inside the loop.

object[] values = (object[]) ThreadWork.GetL ist[key.Key.ToStrin g()]; to
return the exact object and modify it accordingly

string username o= values[4].ToString() for example, since this array object
contains a lot of user info about the user logged into the system. Well the
for loop took that ability away from me. I need to get it back.

for(int x = 0; x < list.Count; x++)
{
object o = list[x];

returns a null object. I hope i am making sense here.
//relevant declaration
Hashtable AccessTable = new Hashtable()

[snip]

object[] valTable = new object[]{

"Server: "+HttpContext.C urrent.Server.M achineName, ...[snip]

[snip]

AccessTable.Add (si,valTable);
Nov 15 '05 #6
"Alvin Bruney" <vapordan_spam_ me_not@hotmail_ no_spamhotmail. com> wrote in message news:<Ox******* ******@tk2msftn gp13.phx.gbl>.. .
yes, but that is really only a work around. There seems to be no way to edit
the collection while iterating thru it since it is read only. We had that
ability in C++ by the way. I'm not starting a new thread here. just saying
that i'll stash that quirk away in the archives of .net faux pas.


You may find this useful:

http://msdn.microsoft.com/library/de...rp01212002.asp

Scroll down to the section headed "Isolation" .
Nov 15 '05 #7
this is a broken link

--
-----------
Got TidBits?
Get it here: www.networkip.net/tidbits
"Michael Petrotta" <mi************ **@yahoo.com> wrote in message
news:50******** *************** ***@posting.goo gle.com...
"Alvin Bruney" <vapordan_spam_ me_not@hotmail_ no_spamhotmail. com> wrote in message news:<Ox******* ******@tk2msftn gp13.phx.gbl>.. .
yes, but that is really only a work around. There seems to be no way to edit the collection while iterating thru it since it is read only. We had that ability in C++ by the way. I'm not starting a new thread here. just saying that i'll stash that quirk away in the archives of .net faux pas.


You may find this useful:

http://msdn.microsoft.com/library/de...rp01212002.asp
Scroll down to the section headed "Isolation" .

Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
4294
by: Randell D. | last post by:
Folks, Ever since reading an interesting article in Linux Format on PHP whereby suggested code writing was made that could enhance performance on a server, I've started testing various bits of code everytime I found more than one method to perform a single task. I timed each method to find which would complete faster. I thought I'd share my...
104
7122
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in...
32
6494
by: Joe Rattz | last post by:
Hmmm, I wrote the following code. I want an array of bools and I want to intialize them to false. bool bits = new bool; foreach(bool bit in bits) { bit = false; } The compiler complains on the "bit = false;" stating that bit is read-only.
15
2664
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a "foreach" loop instead of a "for" loop. This made absolutely no sense to me, but the author had posted his code and timing results. The "foreach"...
13
14454
by: TrintCSD | last post by:
How can I reset the collections within a foreach to be read as a change from within the foreach loop then restart the foreach after collections has been changed? foreach(string invoice in findListBox.listBox2.Items) { listBox2.Items count changed, restart this foreach } Thanks for any help.
4
2558
by: Sjoerd | last post by:
Summary: Use foreach(..) instead of while(list(..)=each(..)). --==-- Foreach is a language construct, meant for looping through arrays. There are two syntaxes; the second is a minor but useful extension of the first: foreach (array_expression as $value) statement
3
33348
by: Akira | last post by:
I noticed that using foreach is much slower than using for-loop, so I want to change our current code from foreach to for-loop. But I can't figure out how. Could someone help me please? Current code is here: foreach ( string propertyName in ht.Keys ) { this.setProperty( propertyName, ht );
29
4215
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could...
2
3219
by: recordlovelife | last post by:
So I am trying to display a title, date, and content of a wordpress blog. Word press provides nice drop in functions to get the job done with simple names like "the_title", and the "the_content" But on the homepage of a site, i wanted to truncate the content to like the first 75 characters and then put "..." (a perfect use of the smarty "truncate"...
7
2266
by: Osiris | last post by:
Just something I would like to share: I just learned the hard way (2 days detective work on a bug) that foreach loops are not at all like for loops, not intuitive at all. BEWARE: arrays and matrices are sparse by design/definition in PHP. I'm doing some matrix manipulation in a Finite Element program. Translating Fortran to PHP, because...
0
7826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8182
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8327
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7935
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8193
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5701
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3818
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2333
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.