Guest User

Guest User

  • Tech Writer
  • 357
  • 120.5k

Expression Trees and Lambdas

May 15 2013 6:12 AM
In the following code, an Expression Tree is being constructed
from a Lambda Expression.

With regards to Expression Trees I know the common practice
is to build from the bottom up but reversed when coded i.e.

ParameterExpression 1st
MemberExpression 2nd
ConstantExpression 3rd
BinaryExpression 4th

LambdaExpression 5th - for executing and compiling to a delegate.

With expressions 1-4 being used to form the Body of the Expression Tree.

My question is from the code example below I cant seem
to see how the Expressions 1-4 are being used to form the Body?

It looks like only some are used?

Regards,
public static class PredicateBuilder
{
    private static readonly MethodInfo asNonUnicodeMethodInfo = 
                typeof(EntityFunctions).GetMethod("AsNonUnicode");
    private static readonly MethodInfo stringEqualityMethodInfo = 
                typeof(string).GetMethod("op_Equality");
 
    public static Expression<Func<TEntity, bool>> ContainsNonUnicodeString<TEntity>(
                IEnumerable<string> source, 
                Expression<Func<TEntity, string>> expression) 
    {
        if (source == null) throw new ArgumentNullException("source");
        if (expression == null) throw new ArgumentNullException("expression");
 
        Expression predicate = null;
        foreach (string value in source)
        {
            var fragment = Expression.Equal(
                expression.Body, 
                Expression.Call(null, 
                    asNonUnicodeMethodInfo, 
                    Expression.Constant(value, typeof(string))), 
                false, 
                stringEqualityMethodInfo);
            if (predicate == null)
            {
                predicate = fragment;
            }
            else
            {
                predicate = Expression.OrElse(predicate, fragment);
            }
        }
 
        return Expression.Lambda<Func<TEntity, bool>>(predicate,
            ((LambdaExpression)expression).Parameters);
    }
}

Answers (3)