简体   繁体   中英

How to use Dictionary in a delegate

I have a Dictionary which I want to filter by different conditions, eg

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, eg

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?

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);
}

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

Func<KeyValuePair<string, string>, bool>

So this is what you need to filter by, 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 as

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM