繁体   English   中英

如何在委托中使用Dictionary

[英]How to use Dictionary in a delegate

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

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

如果您查看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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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