I have a DateRange class that I\'d like to apply to an IQueryable as a where predicate, automatically using the begin and end dates and automatically using an open or closed int
Here's the updated Apply method created after figuring this out.
public IQueryable Apply( IQueryable source, Expression> dateField )
{
Expression predicate;
if (BeginDate.HasValue)
{
if (BeginInclusive)
predicate = Expression.GreaterThanOrEqual( dateField.Body, Expression.Constant( BeginDate, typeof(DateTime) ) );
else
predicate = Expression.GreaterThan( dateField.Body, Expression.Constant( BeginDate, typeof(DateTime) ) );
source = source.Where( Expression.Lambda>( predicate ) );
}
if (EndDate.HasValue)
{
if (EndInclusive)
predicate = Expression.LessThanOrEqual( dateField.Body, Expression.Constant( EndDate, typeof(DateTime) ) );
else
predicate = Expression.LessThan( dateField.Body, Expression.Constant( EndDate, typeof(DateTime) ) );
source = source.Where( Expression.Lambda>( predicate ) );
}
return source;
}
Next, I'll transform it into an extension method, so it can be used like:
DateRange range;
IQueryable q;
q = q.WhereInDateRange( range, x => x.DateField );