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.

Download  Run Code

 
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:

Download  Run Code

 
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:

Download  Run Code

Output:

Unhandled Exception:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

That’s all about filtering a Dictionary<TKey,TValue> in C#.