2013-03-21 28 views
4

我有一個詞典,我想根據不同的條件進行過濾。如何在代表中使用詞典

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

調用這個方法我在做什麼錯?

+0

@Daniel Hilgarth:固定收益型。感謝您指出了這一點。 – Rotte2 2013-03-21 10:45:30

回答

7

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

您可以添加一個註釋,因爲IDictionary 從IEnumerable >繼承,因此需要使用'Func ',但我已經向上投票:-) – sloth 2013-03-21 10:50:01

+0

@DominicKexel:你剛剛添加了那個筆記,我認爲這已經足夠了:) – 2013-03-21 10:55:41

+0

@DanielHilgarth:謝謝。它像一個魅力! – Rotte2 2013-03-21 11:50:52

0

如果你看一下構造函數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")); 
+0

這並不真正做OP的想法。您的'過濾器'方法不會增加*任何*好處。 OP的'Filter'方法返回一個過濾的* dictionary *。 – 2013-03-21 10:39:18

+0

@DanielHilgarth好的,我會添加'ToDictionairy()'到最後,沒問題:P – LukeHennerley 2013-03-21 10:41:11