Gokul's Blog

An Interesting Exception while working with Collections

Leave a comment

I wanted to remove a set of items from a collection.

Tried to achieve it by using

foreach(var item in myObjCollection)
{
myObjCollection.Remove(obj);
}

But the above statement will throw an Exception  saying that the container cannot be modified while enumerating.

I tried to remove the item from collection as follows:

for (int i = 0; i < myObjCollection.Count; ++i) {
 myObjCollection.Remove(myObjCollection[i]);
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Do you think the above statement will work?

The above for statement also throws the same exception.

The resolution to the above problem are

  1. To call myCollection.RemoveAt(0) all the time
  2. Iterate in the reverse order (Starting from myCollection.Count() –1 to 0)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s