2011-05-10 36 views
2

我有一些lambda表達式將在where子句中使用相同的謂詞。因此,我第一次使用謂詞類型。這裏是我有什麼..使用明確定義的謂詞時出現C#錯誤

Predicate<Type> datePredicate = o => o.Date > DateTime.Now.AddDays(-1); 

當我使用它在我的查詢(如下圖),我收到以下錯誤..

錯誤:

The type arguments for method 'System.Linq.Enumerable.Where<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,int,bool>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 

用法:

Type t = collection.Where(datePredicate).SingleOrDefault(); 

有誰知道我在做什麼錯?

+0

您的集合是如何定義的? – 2011-05-10 02:01:01

+0

它是一個列表 Grant 2011-05-10 02:01:47

回答

3

試試這個:

Func<MyObject, bool> datePredicate = (o => o.Date > DateTime.Now.AddDays(-1)); 

collection.Where(datepredicate); 

此外,當你在做.SingleOrDefault(),不知道如何會奇蹟般地變成Type因爲你List<T>不是List<Type>據我知道(因爲Type不有一個Date屬性)。

+0

感謝喬希你的答案奏效。你能告訴我爲什麼我需要使用Func而不是Predicate嗎? – Grant 2011-05-10 02:10:34

+2

這個S/O問題可能會提供一些啓示:http://stackoverflow.com/questions/4317479/func-vs-action-vs-predicate – 2011-05-10 02:13:26

+0

僅僅因爲'.Where'需要'Func '。 – 2011-05-10 02:15:05

0

編譯器無法靜態找出你的o參數是什麼Type。我假設oDateTime類型。編譯器不作出推定:)

Predicate<DateTime> datePredicate = o => o.Date > DateTime.Now.AddDays(-1); 

試試看。

+0

我得到了和以前一樣的錯誤。 – Grant 2011-05-10 02:04:54

+0

我修復了我的答案 - 我想你在我首先回答時編輯了你的問題。 – x0n 2011-05-10 02:06:37