FAQ Item: How do I remove an item in from a generic list inside a foreach loop?
Locked
-
Sunday, June 20, 2010 11:55 AM
How do I remove an item in from a generic list inside a foreach loop?
All Replies
-
Sunday, June 20, 2010 11:56 AM
It is not possible to remove an item from a generic list inside the foreach loop. The underlying collection cannot be modified when enumeration. If we try to remove an item, we will receive an error,
“Collection was modified; enumeration operation may not execute.”
The standard approach is to keep track of the items to remove and then after all of the items are enumerated, loop the” to be removed items” list, and remove each item from the original collection.
Wrong version codes:
System.Collections.Generic.List<object> list = new List<object>();
for (int i = 0; i <= 19;i++ )
{
list.Add(i / 10);
}
foreach (object o in list)
{
if (System.Convert.ToInt32(o) == 1)
{
list.Remove(o);
}
}
Right version codes,
System.Collections.Generic.List<object> list = new List<object>();
for (int i = 0; i <= 19;i++ )
{
list.Add(i / 10);
}
ArrayList arraylist = new ArrayList();
foreach (object o in list)
{
if (System.Convert.ToInt32(o) == 1)
{
arraylist.Add(o);
}
}
foreach (object o in arraylist)
{
list.Remove(o);
}
Related threads:
http://social.msdn.microsoft.com/forums/en/netfxbcl/thread/7ce02724-2813-4f7d-8f3c-b1e3c1fd3019/
For more FAQ about Visual C# General, please see Visual C# General FAQ
- Marked As Answer by MSDN FAQ Sunday, June 20, 2010 11:56 AM

