Filter a Dictionary in C#
This post will discuss how to filter a Dictionary<TKey,TValue> in C#.
Since a Dictionary<TKey,TValue> implements IEnumerable<KeyValuePair<Key,Value>>, we can use the Where() method to filter it. The Where() method filters a sequence of values based on a predicate and is available in the System.Linq namespace. The following code example demonstrates its usage.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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", 5} }; Dictionary<string, int> filtered = dict.Where(x => x.Value % 2 == 0) .ToDictionary(x => x.Key, x => x.Value); Console.WriteLine(String.Join(", ", filtered)); // [B, 2], [D, 4] } } |
The above solution invokes the ToDictionary() method on the filtered sequence to get a new dictionary with associated key-value pairs. If you don’t want to create a new dictionary and need to modify the original dictionary, do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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", 5} }; foreach (var item in dict.Where(x => x.Value % 2 == 0).ToList()) { dict.Remove(item.Key); } Console.WriteLine(String.Join(", ", dict)); // [A, 1], [C, 3], [E, 5] } } |
Note that we’re modifying the underlying collection, ToList() is needed here. Otherwise, System.InvalidOperationException exception will be thrown at the next loop iteration, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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", 5} }; foreach (var item in dict.Where(x => x.Value % 2 == 0)) { dict.Remove(item.Key); } Console.WriteLine(String.Join(", ", dict)); // [A, 1], [C, 3], [E, 5] } } |
Output:
Unhandled Exception:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
That’s all about filtering a Dictionary<TKey,TValue> 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 :)