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?
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;
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.
精彩评论