Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在委托中使用字典_C#_Dictionary_Delegates - Fatal编程技术网

C# 如何在委托中使用字典

C# 如何在委托中使用字典,c#,dictionary,delegates,C#,Dictionary,Delegates,我有一本字典,我想根据不同的条件筛选它 IDictionary<string, string> result = collection.Where(r => r.Value == null).ToDictionary(r => r.Key, r => r.Value); IDictionary result=collection.Where(r=>r.Value==null).ToDictionary(r=>r.Key,r=>r.Value); 我希望将Wher

我有一本字典,我想根据不同的条件筛选它

IDictionary<string, string> result = collection.Where(r => r.Value == null).ToDictionary(r => r.Key, r => r.Value);
IDictionary 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);
}
专用静态IDictionary筛选器(Func exp,IDictionary col)
{
返回col.Where(exp).ToDictionary(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);
Func表达式=r=>r.Value==null;
var结果=过滤器(表达式、集合);

我做错了什么?

在哪里
需要一个
Func
,在您的情况下是
Func

此外,方法的返回类型不正确。它应该使用
T1
T2
而不是
string
。此外,最好对泛型参数使用描述性名称。我使用与字典相同的名称,而不是
T1
T2
TKey
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);
}
专用静态IDictionary筛选器(
函数表达式,IDictionary列)
{
返回col.Where(exp).ToDictionary(r=>r.Key,r=>r.Value);
}

如果查看
Where
扩展方法的构造函数,您将看到

Func

这就是你需要过滤的,试试这个扩展方法

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);
  }
}
公共静态类扩展
{
公共静态IDictionairy筛选器(此IDictionary源,Func filterDelegate)
{
返回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"));
IDictionary Dictionary=new Dictionary();
var result=dictionairy.Filter((x=>x.Key==“YourValue”);

这并不是OP想要的。您的
过滤器
方法不会增加任何好处。OP的
Filter
方法返回一个已过滤的字典。@DanielHilgarth好的,我将
添加到dictionairy()
结尾,没有问题:P@Daniel希尔加思:固定返回类型。感谢您指出这一点。您可以添加一条注释
Func@DominicKexel:你刚才自己加了那张便条,我想这就足够了:)