【发布时间】:2015-01-29 09:48:48
【问题描述】:
我正在尝试构建一个 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”类型的表达式不能用于类型参数 'System.Collections.Generic.IEnumerable'1[T] 来自 'Boolean 包含[T](System.Collections.Generic.IEnumerable'1[T], T)' 方法
【问题讨论】:
-
只是从两个错误我认为你需要把 MakeGenericMethod(typeof(Func
));
标签: c# linq ienumerable contains expressionbuilder