2010-08-03 59 views
8

這是一個普遍的問題,但這裏是我正在尋找一個解決具體情況:方法與謂語參數

我有一個Dictionary<int, List<string>>我想不同的謂詞應用到。我想一個方法,可以照顧多個LINQ查詢,如這些:

from x in Dictionary 
where x.Value.Contains("Test") 
select x.Key 

from x in Dictionary 
where x.Value.Contains("Test2") 
select x.Key 

所以我在尋找一種方法,像這樣:

public int GetResult(**WhatGoesHere** filter) 
{ 
    return from x in Dictionary.Where(filter) 
      select x.Key; 
} 

要使用像這樣:

int result; 

result = GetResult(x => x.Value.Contains("Test")); 
result = GetResult(x => x.Value.Contains("Test2")); 

WhatGoesHere的正確語法是什麼?

+0

Woops,我錯過了正確的類型。我刪除了我的答案。馬克·拜爾的回答很好。 – zneak 2010-08-03 19:10:34

回答

14

您可以使用Func<KeyValuePair<int, List<string>>, bool>

public int GetResult(Func<KeyValuePair<int, List<string>>, bool> filter) 
{ 
    return (from x in Dictionary 
      where filter(x) 
      select x.Key).FirstOrDefault(); 
} 

或者:Predicate<KeyValuePair<int, List<string>>>。我認爲在.NET 3.5中引入的Func最近爲preferred

您正在使用x來表示最後一個示例中的兩個不同的事情,這會導致編譯錯誤。嘗試改變其中一個x s到別的東西:

x = GetResult(y => y.Value.Contains("Test1")); 
+0

啊,我以爲我走在正確的道路上。我在做Predicate >>但我想這沒有多大意義。謝謝。 – Ocelot20 2010-08-03 19:13:07