Collection was modified; enumeration operation may not execute. C?

This is the heart of the problem. You cannot remove an item from a collection as you are iterating over it in a foreach Your options are to make a local copy of the list prior to the loop, loop over the copy, and remove from the original. Or you can keep a separate list of items to remove after you finish the original loop.

Or you can switch to a for loop and iterate over it backwards, which allows you to remove items from the end as you go.

Foreach (PC_list x in onlinelist) { onlinelist. Remove(x); // cannot do this } This is the heart of the problem. You cannot remove an item from a collection as you are iterating over it in a foreach.

Your options are to make a local copy of the list prior to the loop, loop over the copy, and remove from the original. Or you can keep a separate list of items to remove after you finish the original loop. Or you can switch to a for loop and iterate over it backwards, which allows you to remove items from the end as you go.

While you're here, if you are not stuck working with C# 1 / . NET 1.1 / Visual Studio 2003, you might want to consider switching from ArrayList to the stronger List, where T is the type of the object in the collection. In your case, that would be a List.

You can find it at System.Collections.Generic.List. And since your question is tagged multithreading, it would also be a smart idea to consult the collections built with concurrency in mind.

Thank you. It was really helpful – Jasim Khan Afridi Oct 14 at 0:46.

You cannot modify onlinelist in a foreach block. This is why you get this error. Try this: ArrayList RemoveList = new ArrayList(); foreach (PC_list x in onlinelist) { if ((nowtime.

Subtract(x. Time)). TotalSeconds > 5) { Invoke(new MethodInvoker(delegate { index = Main_ListBox.

FindString(x. PcName); if(index! = ListBox.

NoMatches) Main_ListBox.Items. RemoveAt(index); })); RemoveList. Add(x); //Thread.

Sleep(500); } } foreach (PC_list x in RemoveList) { onlinelist. Remove(x); }.

Yeah, your logic is broken. You're asking the iterator to move to the next object after x in the list, but you've removed x from the list, so there is no such thing. There are a lot of workarounds, but the traditional way to do it is to remove the previous object at the top of the loop.(This only works for collections that do not reorganize on removals.).

That's not quite it. You can't remove ANY item from the list while you're in the foreach loop. – phoog Oct 14 at 6:03.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions