Hi there
I'm trying to remove an hashtable that is inside another, that have ["OK"] = 0 for example.
but i'm recieving the error:
Collection was modified; enumeration operation may not execute."
I'm using the following loop:
foreach (string ikey in gridNum.Keys)
{
Hashtable aux = (Hashtable)gridNum[ikey];
if (aux["OK"].ToString().Trim() == "1")
gridNumero.Remove(ikey);
}
gridNum is the Hashtable that have like 10 hashtables or more inside
each of that 10 ashtables have values like OK = 0/1, value = blabla, bla = asaasa
Is there a way to make this loop to work
Thank you

Collection was modified; enumeration operation may not execute
Mohamad Tantawy
Think about what you are doing real quick... you are iterating through each item in a list of items within your collection, when midway through you suddenly remove one... how does the system know where to pick up
That is the problem you are running into, and to avoid it we need to work slightly differently with the, namely making another list of what we want to remove so that it can be removed separately.
Try the following:
List<string> tablesNamesToRemove = new List<string>();
foreach (string ikey in gridNum.Keys)
{
Hashtable aux = (Hashtable)gridNum[ikey];
if (aux["OK"].ToString().Trim() == "1")
tablesNamesToRemove.Add(ikey);
}
foreach (string name in tablesNamesToRemove)
{
gridNum.Remove(name);
}
In this example, instead of removing the object right away, we note it's name to a seperate list and once complete we run through every name in that list and remove it from the actual object container.
Does this work for you
kalyanic
yes it works
thank you for your help
final code looks like this:
ArrayList Lremove = new ArrayList();
foreach (string ikey in gridNum.Keys)
{
Hashtable aux = (Hashtable)gridNum[ikey];
if (aux["OK"].ToString().Trim() == "0")
Lremove.Add(ikey);
}
foreach (string name in Lremove )
{
gridNum.Remove(name);
}
Xaero
Alternately, we can create an array of the keys first:
string[] keys = new string[gridNum.Keys.Count];
gridNum.Keys.CopyTo(keys, 0);
foreach(string ikey in keys)
{
Hashtable aux = (Hashtable)gridNum[ikey];
if (aux["OK"].ToString().Trim() == "0")
gridNum.Remove(name);
}