Rotte2
Rotte2

Reputation: 183

How to use Dictionary in a delegate

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?

Upvotes: 4

Views: 362

Answers (2)

LukeHennerley
LukeHennerley

Reputation: 6444

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

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

Upvotes: 7

Related Questions