LinqKit PredicateBuilder Examples
I am trying to get the examples working found at http://www.albahari.com/nutshell/predicatebuilder.aspx
I have the following code:
Any Suggestions would be greatly appreciated.
I have the following code:
My question is between method 1 and method 2, the guts of the code are identical but when I call the Method 2 PriceList.IsCurrent I get the following error.
public partial class PriceList
{
public string Name { get; set; }
public string Desc {get;set;}
public DateTime? ValidFrom {get;set;}
public DateTime? ValidTo{get;set;}
public static Expression> IsCurrent()
{
return p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now) && (p.ValidTo == null || p.ValidTo >= DateTime.Now);
}
}
void Main()
{
List plList = new List()
{
new PriceList(){ Name="Billy", Desc="Skilled", ValidFrom = DateTime.Now.AddDays(-10.0) , ValidTo= DateTime.Now.AddDays(1.0) },
new PriceList(){ Name="Jamie", Desc="Quick Study",ValidFrom =DateTime.Now.AddDays(-10.0) , ValidTo= DateTime.Now.AddDays(1.0) },
new PriceList(){Name= "Larry", Desc= "Rookie",ValidFrom = DateTime.Now.AddDays(-10.0) , ValidTo= DateTime.Now.AddDays(1.0) }
};
// Method 1
var myResultList = plList.Where ( p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now)
&& (p.ValidTo == null || p.ValidTo >= DateTime.Now)).Dump();
// Method 2
plList.Where(PriceList.IsCurrent()).Dump(); // This does not work currently
}
Any Suggestions would be greatly appreciated.
'System.Collections.Generic.List' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments
Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.IQueryable'
Comments
1. The nutshell examples are based on db entities which are Linq.Table<T> classes. This class implements the IQueryable interface which has a Where(Expression) method: 2. As List<T>.Where() accepts a Func<T, bool> predicate, you can compile the Expression to a Func first: See also: http://stackoverflow.com/questions/1217749/how-to-convert-an-expressionfunct-bool-to-a-predicatet
In this example, you could have defined the function simpler this way: No .Compile() or .AsQueryable() necessary
But you probably shouldn't, as the experts explain here:
http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct