Search code examples
c#linqlambdapredicate

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?


Solution

  • 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).