C# Filter a dictionary
By FoxLearn 1/21/2025 7:16:22 AM 7
For example:
using System.Linq; var dictionary = new Dictionary<string, int>() { ["apple"] = 5, ["banana"] = 8, ["cherry"] = 12 }; // filter var filterList = dictionary.Where(kvp => kvp.Key.Length > 5); // back to a dictionary var newDictionary = filterList.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
You can also use the dictionary constructor new Dictionary<string, int>(filterList)
instead of ToDictionary()
if you prefer.
This produces a new dictionary with the filtered items:
[banana, 8] [cherry, 12]
Where()
produces a list (actually an IEnumerable
) of KeyValuePair
objects. Most of the time, you’ll want the result as a dictionary, so you’ll need to use ToDictionary()
to convert the list back into a dictionary.
Filter by Removing Items
Alternatively, you can remove unwanted items directly from the original dictionary. This modifies the dictionary in place, rather than creating a new one. The easiest way to do this is by using Where()
to filter the items and then removing the items in a loop.
using System.Linq; var dictionary = new Dictionary<string, int>() { ["apple"] = 5, ["banana"] = 8, ["cherry"] = 12 }; // filter var filterList = dictionary.Where(kvp => kvp.Key.Length <= 5); // remove from original dictionary foreach(var kvp in filterList) { dictionary.Remove(kvp.Key); }
This removes the items from the original dictionary, which now has only one item left:
[cherry, 12]
Before .NET Core 3.0 - Use .ToList() When Removing
In .NET Core 3.0 and later, you can remove items from a dictionary while looping over it.
However, in versions before .NET Core 3.0, attempting to do so directly would cause an InvalidOperationException: Collection was modified; enumeration operation may not execute
.
If you're using a version prior to .NET Core 3.0, you should call .ToList()
to avoid this exception when removing items:
// filter var filterList = dictionary.Where(kvp => kvp.Key.Length <= 5); // remove from original dictionary foreach(var kvp in filterList.ToList()) { dictionary.Remove(kvp.Key); }