views:

178

answers:

2

I'm trying to build an expression tree (still) but getting further! I need to create a BinaryExpression to perform an 'In' comparison between a Member and a collection of items. Hence, the expression should return true if the member is contained within the items.

This obviously does not exist:

Expression.MakeBinary(ExpressionType.In, memberExpression, constantExpression);

constantExpression is a ConstantExpression of type IEnumerable<T> while memberExpression is a MemberExpression of type T.

How would I create such an expression?

+3  A: 

You'd usually use "Contains" instead - that's how you typically write a LINQ query which would map to "IN" in SQL:

var query = from user in db.Users
            where specialUsers.Contains(user.Name)
            select user.Id;
Jon Skeet
That was my first thought but I'm kind of lost on how to translate such a LINQ query into an expression tree.
Adam Driscoll
@Adam: The easiest thing to do is try it :) Create an expression, then use Reflector to see what the compiler's done. Basically there'll be a call to Queryable.Where, with an expression which represents a call to `Contains` on a constant (the `specialUsers` collection here) passing in the evaluated `user.Name` as an argument.
Jon Skeet
Did not realize that LINQ compiled out that way. This should save me some time. Thanks!
Adam Driscoll
A: 

Just wanted to added how I ultimately got this to work:

var callExpression = Expression.Call(typeof(Enumerable), "Contains", new Type[] {memberExpression.Type}, constantExpression, memberExpression);

Compiling and invoking the callExpression will yield whether or not a memberExpression is within the constantExpression collection.

Adam Driscoll