Delete entries while iterating over a dictionary in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 2} }; var toRemove = dict.Where(kvp => kvp.Value == 2).ToList(); foreach (var item in toRemove) { dict.Remove(item.Key); } Console.WriteLine(String.Join(", ", dict)); // [A, 1], [C, 3], [D, 4] } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 2} }; foreach (var item in new Dictionary<string, int>(dict)) { if (item.Value == 2) { dict.Remove(item.Key); } } Console.WriteLine(String.Join(", ", dict)); // [A, 1], [C, 3], [D, 4] } } |
Alternatively, you can convert the dictionary to a list and iterate over it, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 2} }; foreach (var item in dict.ToList()) { if (item.Value == 2) { dict.Remove(item.Key); } } Console.WriteLine(String.Join(", ", dict)); // [A, 1], [C, 3], [D, 4] } } |
That’s all about deleting entries while iterating over a dictionary in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)