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:你刚才自己加了那张便条,我想这就足够了:)