如何在委托中使用字典

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

我做错了什么?

@Daniel Hilgarth:修正了返回类型。感谢您指出。 - Rotte2
2个回答

7

Where需要一个Func<TSource, bool>,在您的情况下是Func<KeyValuePair<TKey,TValue>,bool>

此外,您的方法返回类型不正确。它应该使用T1T2而不是string。另外,最好为通用参数使用描述性名称。我使用与字典相同的名称-TKeyTValue

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

你可以添加一条注释,说明需要 Func<KeyValuePair<TKey, TValue>,因为 IDictionary<TKey, TValue> 继承自 IEnumerable<KeyValuePair<TKey, TValue>>,但我已经点赞了 :-) - sloth
@DominicKexel:你刚刚自己添加了那个注释,我认为这已经足够了 :) - Daniel Hilgarth

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

那并不是 OP 想要的。你的 Filter 方法并没有增加任何好处。OP 的 Filter 方法返回一个经过筛选的 字典 - Daniel Hilgarth
@DanielHilgarth 好的,我会在结尾处添加 ToDictionairy(),没问题 :P - LukeHennerley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接