我目前是第一次使用 ASP 动态数据,并且正在尝试构建一个过滤器。我们的用户需要根据项目是否是所选父项的子项(我们的项目可以有多个父项)来定位列表中的项目。
所讨论的项目是分段,每个分段都有一个名为 RouteIds 的属性,其类型为 IEnumerable,它是该分段的所有父 Id 的集合。
我已经在过滤器中重写了 GetQueryable 方法,但我不断在显示的最后一行抛出异常:
ConstantExpression ce = Expression.Constant(int.Parse(this.ddlRouteNames.SelectedValue));
ParameterExpression pe = Expression.Parameter(source.ElementType);
MemberExpression me = Expression.Property(pe, this.Column.Name);
var callExpression = Expression.Call(typeof(Enumerable), "Contains", new Type[] { me.Type }, ce, me);
我们的想法是,用户将从 DropDownList 中选择适当的路线,然后我会检查该段的 RouteIds 属性是否包含该路线的 Id。
有关如何使其正常工作的任何指示?
编辑 - 这是异常(exception):
No generic method 'Contains' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.
最佳答案
您的代码中有两个问题:
- 你的参数是倒退的。第一个参数必须是集合,第二个参数必须是您要搜索的项目。
- 您的类型参数是
IEnumerable<int>
,而它应该只是int
.
所以,固定代码是:
var callExpression = Expression.Call(
typeof(Enumerable), "Contains", new[] { typeof(int) }, me, ce);
但看起来你的表达的所有部分实际上并不是动态的,所以也许像下面这样的东西也可以工作:
Expression<Func<Segment, bool>> expression =
s => s.RouteIds.Contains(int.Parse(this.ddlRouteNames.SelectedValue));
关于c# - 如何构建 IEnumerable<int>.Contains() 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16347794/