How to use a dictionary in a delegate

I have a dictionary that I want to filter in different conditions, for example.

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 does the actual filtering, for example

 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 is not compiled.

I tried calling this method 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?

+4
source share
2 answers

Where wants Func<TSource, bool> , in your case Func<KeyValuePair<TKey, TValue>, bool> .

In addition, your return type is incorrect. It should use T1 and T2 instead of string . In addition, it is better to use descriptive names for general 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); } 
+7
source

If you look at the constructor for the Where extension method, you will see

Func<KeyValuePair<string, string>, bool>

So here is what you need to filter out, try this extension method.

 public static class Extensions { public static IDictionairy<TKey, TValue> Filter<TKey, TValue>(this IDictionary<TKey, TValue> source, Func<KeyValuePair<TKey, TValue>, bool> filterDelegate) { return source.Where(filterDelegate).ToDictionary(x => x.Key, x => x.Value); } } 

Call

 IDictionary<string, string> dictionairy = new Dictionary<string, string>(); var result = dictionairy.Filter((x => x.Key == "YourValue")); 
0
source

All Articles