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:
Note that you don’t have to use
AndAlsoonly afterAnd, despite the confusing names.The difference between them is much like the difference between
&and&&–AndAlsois a logical And operator, andAndis a bitwise operator.