This question already has an answer here:
- Remove Item in Dictionary based on Value 6 answers
The question should be clear from the title itself. I need to check if an item exist in the dictionary and remove it from the dictionary in C#. The only catch is that i have to do this using only the value item and not the key.
The declaration is as below:
IDictionary<string, myCustomClassObject> clients = new IDictionary<string, myCustomClassObject>();
Now i fill in the dictionary by:
clients["key"] = myCustomClassObject1;
Now how can i find and remove this item myCustomClassObject1
from my Dictionary. I only want to use the value item and not the key
Is this doabale...if so please guide... regards
Edit: Thank you all....got valuable comments...probably have some thinking to do ...thanks
It depends on how you need it to perform. If you can accept
O(N)
performance, you could just do something like:However, if you need faster you would need two dictionaries - one the reverse of the other (i.e. keyed by the instances). So when adding, you would do:
so you can do (to remove-by-value):
or similarly (to remove-by-key):
Use, Following will remove only first matching value
Or if you want to remove all matching values,
It's not very efficient to search a dictionary by it's values. However, you can use Linq to find all entries with a given value.
This should do it. It removes all clients having a given value.
Or create a new dictionary without the values you want removed
If the collection only contains one item with the value to be removed then you can use one of the other answers here, which will work just fine.
However, if your collection can have multiple items with the same value then you need to be careful.
You cannot modify a collection while iterating over it, so you will need to find the keys of all the items that you want to remove in one loop and put them in a list, and then iterate over that list in a separate loop to delete the items.
For example: