[英]How to use Delegate in C# for Dictionary<int, List<string>>
[英]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>
。
此外,您的方法的返回類型不正確。 它應該使用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);
}
如果您查看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.