Need help creating an expression tree for Where clause

c# expression-trees linq-to-entities


I need to create an expression tree, which I can pass along as predicate argument in Where clause to Linq To Enities query.

public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source,
    Expression<Func<TSource, bool>> predicate);

Expression tree must be equivalent to where clause specified as below:

var query = context.Products.Select(product => 
    new { product.Name, product.Color });

var arr = "Red;Black".Split(';');
query = query.Where(obj => arr.Contains(obj.Color));
11/24/2012 4:06:48 PM

Accepted Answer

Googled it out!

var paramExpr = Expression.Parameter(typeof(TSource), "src");
var memberExpr = (MemberExpression)property.Body;

List<Expression> arrayInits = new List<Expression>();

var arrExpr = Expression.Constant(((string)values[0]).Split(new char[] { ';' }));

MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");

var containsExpression = Expression.Call(null, contains, arrExpr, memberExpr);
var containsLambda = Expression.Lambda<Func<TSource, bool>>(containsExpression, property.Parameters);

And it works!

11/25/2012 4:39:45 AM

Popular Answer

public static Expression<Func<T, bool>> CreateContainsExpression<T>(T obj, string[] array)
    var paramExpr = Expression.Parameter(typeof(T), "obj");
    var arrExpr = Expression.Constant(array);

    var colourPropExpr = Expression.Property(paramExpr, "Color");
    MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");

    var containsExpr = Expression.Call(arrExpr, containsMethod, colourPropExpr);
    return Expression.Lambda<Func<T, bool>>(containsExpr, paramExpr);

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow