I am busy writing an dynamic AND filter on a IQueryable Linq object, so far this is my code and it works:
public static IQueryable<T> FilterHeaders<T>(this IQueryable<T> records, IEnumerable<ListHeader> headers)
{
// Build linq expression to filter queryable
if (headers != null)
{
var param = Expression.Parameter(typeof(T), "x");
var body = Expression.And(Expression.Constant(true), Expression.Constant(true));
foreach (var header in headers)
{
if (header.Filter != null && !String.IsNullOrWhiteSpace(header.Filter.Value))
{
var property = Expression.PropertyOrField(param, header.HeaderType.ToString());
var value = Expression.Constant(header.Filter.Value.Trim(), typeof(string));
body = Expression.AndAlso(body, Expression.Call(property, "Contains", null, value));
}
}
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return records.Where(lambda);
}
return records;
}
I have initialized my expression body with Expression.And(Expression.Constant(true), Expression.Constant(true))
. It seems to me that there should be a better way...
How?
Can't you just do:
var body = Expression.Constant(true);
Note that you don't have to use AndAlso
only after And
, despite the confusing names.
The difference between them is much like the difference between &
and &&
- AndAlso
is a logical And operator, and And
is a bitwise operator.
Replace
Expression.And(Expression.Constant(true), Expression.Constant(true));
With
Expression.Constant(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With