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?
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).
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.
精彩评论