将List.Contains转换为Expression Tree [英] Convert List.Contains to Expression Tree
问题描述
相关:
在上一个问题的下面,我遇到了要编写Expression Tree
版本的查询:
In the following of my previous question I faced with this query that I want to write Expression Tree
version:
List<byte?> lst = new List<byte?>{1,2};
from a in myTbl
where a.Age = 20 && lst.Contains(a.Status)
select a
我写这段代码:
List<byte?> lst = new List<byte?>{1,2};
var param = Expression.Parameter(typeof(T), "o");
var body = Expression.AndAlso(
Expression.Equal(
Expression.PropertyOrField(param, "Age"),
Expression.Constant(20)
),
Expression.Call(Expression.PropertyOrField(param, "Status"),
"Contains",
Type.EmptyTypes,
Expression.Constant(lst)));
var lambda = Expression.Lambda<Func<T, bool>>(body, param);
return lambda;
我得到了错误:
类型'System.Nullable'1 [System.Byte]'上不存在方法'Contains'."
"No method 'Contains' exists on type 'System.Nullable`1[System.Byte]'."
请帮助我找到问题.
谢谢
推荐答案
问题是您已将两个参数切换为Expression.Call
,您的代码正在尝试创建无意义的表达式o.Status.Contains(lst)
.
The problem is that you have switched two arguments to Expression.Call
, your code is trying to create the nonsensical expression o.Status.Contains(lst)
.
您需要切换两个参数:
Expression.Call(Expression.Constant(lst),
"Contains",
Type.EmptyTypes,
Expression.PropertyOrField(param, "Status"))
这是假设您使用的LINQ提供程序了解List<T>.Contains()
.如果需要Enumerable.Contains()
,请查看Ivan Stoev的答案.
This is assuming that the LINQ provider you're using understands List<T>.Contains()
. If you need Enumerable.Contains()
, then have a look at Ivan Stoev's answer.
这篇关于将List.Contains转换为Expression Tree的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!