Grant
Grant

Reputation: 11356

C# error when using explicitly defined Predicate

i have a number of lambda expressions that will be using the same predicate in a where clause. As such i am using the predicate type for the first time. Here is what i have..

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

When i use it in my query (below), i am getting the following error..

Error:

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.

Usage:

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

Does anyone know what i am doing wrong?

Upvotes: 2

Views: 1085

Answers (2)

Josh M.
Josh M.

Reputation: 27783

Try this:

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

collection.Where(datepredicate);

Also when you're doing .SingleOrDefault(), not sure how that will magically turn into a Type since your List<T> is not a List<Type> as far as I know (since Type doesn't have a Date property).

Upvotes: 3

x0n
x0n

Reputation: 52420

The compiler cannot statically figure out what Type your o parameter is. I would presume o is of type DateTime. Compilers don't make presumptions :)

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

Try that.

Upvotes: 0

Related Questions