Linq expression - How to initialize with Expression.And correctly?

I am busy writing a dynamic IO filter on an IQueryable Linq object, as long as 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 initialized the body of the Expression.And(Expression.Constant(true), Expression.Constant(true)) expression Expression.And(Expression.Constant(true), Expression.Constant(true)) . It seems to me that there should be a better way ...

How?

+4
source share
2 answers

Can't you just do:

 var body = Expression.Constant(true); 

Note that you do not need to use AndAlso only after And , despite the confusing names. The difference between them is very similar to the difference between & and && - AndAlso is the logical operator of And, and And is the bitwise operator.

+6
source

Replace

 Expression.And(Expression.Constant(true), Expression.Constant(true)); 

FROM

 Expression.Constant(true); 
+1
source

All Articles