How to use Dictionary in a delegate
c#, delegates, dictionary
Solution
`Where` wants a `Func<TSource, bool>`, in your case `Func<KeyValuePair<TKey, TValue>, bool>`.
Furthermore, your return type of the method is incorrect. It should use `T1` and `T2` instead of `string`. Additionally, it is better to use descriptive names for the generic parameters. Instead of `T1` and `T2` I use the same names as the dictionary - `TKey` and `TValue`:
private static IDictionary<TKey, TValue> Filter<TKey, TValue>(
Func<KeyValuePair<TKey, TValue>, bool> exp, IDictionary<TKey, TValue> col)
{
return col.Where(exp).ToDictionary(r => r.Key, r => r.Value);
}
Problem
I have a Dictionary which I want to filter by different conditions, e.g. ``` IDictionary<string, string> result = collection.Where(r => r.Value == null).ToDictionary(r => r.Key, r => r.Value); ``` I would like to pass the Where clause as a parameter to a method that performs the actual filtering, e.g. ``` private static IDictionary<T1, T2> Filter<T1, T2>(Func<IDictionary<T1, T2>, IDictionary<T1, T2>> exp, IDictionary<T1, T2> col) { return col.Where(exp).ToDictionary<T1, T2>(r => r.Key, r => r.Value); } ``` This does not compile, though. I have tried to call this method by using ``` Func<IDictionary<string, string>, IDictionary<string, string>> expression = r => r.Value == null; var result = Filter<string, string>(expression, collection); ``` What am I doing wrong?