This post will discuss how to delete entries while iterating over a dictionary in C#.

It is not allowed to modify a dictionary (add/remove entries from it) while iterating over it; otherwise, InvalidOperationException will be thrown at the next loop iteration to avoid non-deterministic behavior. The idea is to create a collection of items you want to delete, iterate over it, and delete each entry from the dictionary. For example, the following code removes all entries from the dictionary having value 2.

Download  Run Code

 
Another option is to iterate over the copy of the dictionary and remove the matching key-value pairs from it. For example, the following code creates a copy of the dictionary and removes all entries with value 2.

Download  Run Code

 
Alternatively, you can convert the dictionary to a list and iterate over it, as shown below:

Download  Run Code

That’s all about deleting entries while iterating over a dictionary in C#.