4

さまざまな条件でフィルタリングしたい辞書があります。

IDictionary<string, string> result = collection.Where(r => r.Value == null).ToDictionary(r => r.Key, r => r.Value);

Where 句をパラメーターとして、実際のフィルタリングを実行するメソッドに渡したいと思います。

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

ただし、これはコンパイルされません。

を使用してこのメ​​ソッドを呼び出そうとしました

Func<IDictionary<string, string>, IDictionary<string, string>> expression = r => r.Value == null;
var result = Filter<string, string>(expression, collection);

私は何を間違っていますか?

4

2 に答える 2

7

WhereFunc<TSource, bool>あなたの場合、を望んでいますFunc<KeyValuePair<TKey, TValue>, bool>

さらに、メソッドの戻りタイプが正しくありません。の代わりにT1とを使用する必要があります。さらに、一般的なパラメーターにはわかりやすい名前を使用することをお勧めします。の代わりに、私は辞書と同じ名前を使用します-そして:T2stringT1T2TKeyTValue

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);
}
于 2013-03-21T10:33:04.510 に答える
0

Where拡張メソッドのコンストラクターを見ると、

Func<KeyValuePair<string, string>, bool>

これは、フィルタリングする必要があるものです。この拡張メソッドを試してください。

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

として呼び出す

IDictionary<string, string> dictionairy = new Dictionary<string, string>();
var result = dictionairy.Filter((x => x.Key == "YourValue"));
于 2013-03-21T10:36:47.173 に答える