The simplest way to filter a dictionary is by using the Linq Where() + ToDictionary() methods. Here’s an example:
using System.Linq;
var dictionary = new Dictionary<string, int>()
{
["fish"] = 3,
["cat"] = 5,
["dog"] = 10
};
//filter
var filterList = dictionary.Where(kvp => kvp.Key.StartsWith("d"));
//back to a dictionary
var newDictionary = filterList.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Code language: C# (cs)
Note: You can use the Dictionary constructor (new Dictionary<string, int>(filterList)) instead of ToDictionary() if you prefer.
This produces a new dictionary with the filtered item:
[dog, 10]
Code language: plaintext (plaintext)
Where() produces a list (actually an IEnumerable) of KeyValuePair objects. Most of the time, you’ll want the results as a dictionary, not a list. This is why you’ll want to use ToDictionary() to convert this list to a dictionary.
Filter by removing items
The other option is to select and remove items from the dictionary that you don’t want. This modifies the original dictionary, instead of producing a new one. The simplest way to do this is to use the Linq Where() method + remove the items in a loop. Here’s an example of how to do that:
using System.Linq;
var dictionary = new Dictionary<string, int>()
{
["fish"] = 3,
["cat"] = 5,
["dog"] = 10
};
//filter
var filterList = dictionary.Where(kvp => !kvp.Key.StartsWith("d"));
//remove from original dictionary
foreach(var kvp in filterList)
{
dictionary.Remove(kvp.Key);
}
Code language: C# (cs)
This removes items from the original dictionary, which now has one item remaining:
[dog, 10]
Code language: plaintext (plaintext)
Before .NET Core 3.0 – Use .ToList() when removing
In .NET Core 3.0, they made it so you could remove from a dictionary while looping over it. Before that, you’d get an exception trying to do that: InvalidOperationException: Collection was modified; enumeration operation may not execute.
If you’re using a version before .NET Core 3.0, use .ToList() to avoid this exception while removing items:
//filter
var filterList = dictionary.Where(kvp => !kvp.Key.StartsWith("d"));
//remove from original dictionary
foreach(var kvp in filterList.ToList())
{
dictionary.Remove(kvp.Key);
}
Code language: C# (cs)