c# - 如何在委托(delegate)中使用字典

标签 c# dictionary delegates

我有一个字典,我想根据不同的条件进行过滤,例如

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

我做错了什么?

最佳答案

Where想要一个 Func<TSource, bool> ,在你的情况下 Func<KeyValuePair<TKey, TValue>, bool> .

此外,您的方法返回类型不正确。它应该使用 T1T2而不是 string .此外,最好为通用参数使用描述性名称。而不是 T1T2我使用与字典相同的名称 - 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);
}

关于c# - 如何在委托(delegate)中使用字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15544962/

相关文章:

ios - UITableView 委托(delegate)

ios - ARC - 如何管理那些需要 __unsafe_unretained 的属性?

python - 键是 Python 中的一对整数的字典

python - Python 3 中自定义类的迭代器

python - 元组到字典 :one key and multiple values

c# - 如何将实体从一个 Entity Framework 上下文复制到另一个 Entity Framework 上下文?

Cocoa:当应用程序位于最前面时强制执行 NSUserNotification

c# - 如何在 WPF 图像中显示位图

c# - 什么 R# 设置正在重新格式化这一行?

c# - 罗马数字减法不转换