Need help creating an expression tree for Where clause

c# expression-trees linq-to-entities

Question

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));

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!


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);
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why