foreach

Im using a hashtable to hold all my connected clients, I have a loop statment that sends data to each client to make sure there all connected and im using a foreach statment to go through the hashtable to fet the clients name to send the data. now if the server cant send the data to a client it will remove the client name from the hashtable, when the code loops through again I get a error saying the collection was modified if I click continue the loop will exit. how can I fix this little problem



Answer this question

foreach

  • Sunil_pachunde

    hi,

    did you try to exit the loop after deleting a entry and to go in afterwards again

    You may replace the foreach statement by a for statement that cycles throug the list. But remember after deleting something from your table you should decrement your count-variable, otherwise you skipe an element Smile

  • Mikaelm

    Yet another approach....

    You could keep another Hashtable of inactive clients and then remove these after iterating over the client list.

    Hashtable clients = new Hashtable();
    // whatever fills the client hashtable


    // before iterating over clients ensure you have
    //  an empty inactive client table
    Hashtable inactiveClients = new Hashtable();
    foreach (DictionaryEntry client in clients)
    {
       // communicate with client
       // if communication fails add them to the inactive list
       inactiveClients.Add(client.Key, client.Value);
    }

    // now remove the inactive clients
    foreach (DictionaryEntry inactiveClient in inactiveClients)
    {
       clients.Remove(inactiveClient.Key);
    }


    If you don't need the client "value" for removal you could use an ArrayList to keep track of the inactive clients.  Here's code for when your Hashtable keys are simple strings:

    // before iterating over clients ensure you have
    //  an empty inactive client list
    ArrayList inactiveClients = new ArrayList();
    foreach (DictionaryEntry client in clients)
    {
       // communicate with client
       // if communication fails add them to the inactive list
       inactiveClients.Add(client.Key);
    }

    // now remove the inactive clients
    foreach (string inactiveClient in inactiveClients)
    {
       clients.Remove(inactiveClient);
    }

    (Code was not pasted from IDE so there could be syntax errors)


  • QuanT

    Hashtables do not allow you get values by index, so using a for loop as Ralph suggested will not help.

    If a collection gets modified during a foreach (or a enumeration), then a InvalidOperationException will be thrown. To get around this, you could create a 'snapshot' of the Hashtable and then perform a foreach on it:


    Hashtable clients = new Hashtable();

    ....

    Hashtable snapshot = new Hashtable(clients);

    foreach (DictionaryEntry entry in snapshot)
    {
       ...
    }

     




  • foreach