qwr qwr
qwr qwr

Reputation: 1059

How to remove a pair in hashtable knowing the hash.value

I am sure that my in my hashtable, there is no duplicated value and key. Here is my code:

     private void checkclientleave(string content)
    {
        if (content == "I am leaving the room")
        {
            foreach (DictionaryEntry dict in clientsInroom)
            {
                 if (dict.Value == clientSocket)
                    clientsList.Remove(dict.Key);
            }
   }
   }

The value of my hashtable is the socket for each client. The key of my hashtable is the name of each client. I got some unknown error: collection was modified enumeration operation may not execute Anyone has any idea??

Upvotes: 0

Views: 5745

Answers (3)

walther
walther

Reputation: 13600

Removal of items during an iteration IS possible. You just need to approach it differently. You would need to use "for" loop and iterate backwards.

I know, this probably isn't necessary in your specific situation, but I thought it might help someone else who finds this question later.

Look her for a more detailed answer: How to remove elements from a generic list while iterating over it?

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500385

I got some unknown error: collection was modified enumeration operation may not execute Anyone has any idea??

That's not an unknown error - that's a well-documented error:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

And for MoveNext:

InvalidOperationException [thrown if] The collection was modified after the enumerator was created.

You're iterating over a dictionary, and you can't add or remove entries while you're iterating. If you know that you won't have any other values, you can just return from your method as soon as you've found the key which matches the given value:

if (dict.Value == clientSocket)
{
    clientsList.Remove(dict.Key);
    return;
}

Another alternative would be to use LINQ:

var key = clientsInRoom.Where(pair => pair.Value == clientSocket)
                       .Select(pair => pair.Key)
                       .FirstOrDefault();
if (key != null)
{
    clientsInRoom.Remove(key);
}

Upvotes: 2

MiMo
MiMo

Reputation: 11953

It looks wrong to me - I assume that

               clientsList.Remove(dict.Key);

should actually be

               clientsInRoom.Remove(dict.Key);

and if such is the case you are modifying a dictionary within a foreach on the same dictionary, that would cause an exception.

Upvotes: 0

Related Questions