我正在尝试构建一个 LINQ 表达式,以过滤来自 int 属性的值:
protected IQueryable<T> Some(IEnumerable<int> ids)
{
var parameter = Expression.Parameter(typeof(T), "x");
// "Col_id" (int property)
var property = Expression.Property(parameter, "Col_id");
MethodInfo method = typeof(Enumerable).
GetMethods().
Where(x => x.Name == "Contains").
Single(x => x.GetParameters().Length == 2).
MakeGenericMethod(typeof(T));
// ids = { 2, 4, 8 } etc...
var value = Expression.Constant(ids, typeof(IEnumerable<int>));
var containsMethod = Expression.Call(method, property, value); // exception
var aDelegate = Expression.Lambda<Func<T, bool>>(containsMethod, parameter);
table = myDataContext.GetTable<T>();
return table.AsQueryable().Where(aDelegate);
}
我试图得到类似的东西:(x => ids.Contains(x.Col_id))
,但抛出异常:
'System.Int32' 类型的表达式不能用于来自 'Boolean Contains[T](System.Collections.Generic.IEnumerable'1[T], T) 的类型参数 'System.Collections.Generic.IEnumerable'1[T] ' 方法