Search code examples
c#.netlinqexpression-trees

Expression Tree Binary Expression for an 'In' operation


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?


Solution

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