Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Expression - How to initialize with Expression.And properly?

Tags:

c#

dynamic

linq

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?

like image 631
321X Avatar asked Jun 20 '12 11:06

321X


2 Answers

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.

like image 122
Kobi Avatar answered Nov 14 '22 21:11

Kobi


Replace

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

With

Expression.Constant(true); 
like image 31
Kishore Kumar Avatar answered Nov 14 '22 22:11

Kishore Kumar