gpt4 book ai didi

c# - 如何构建 IEnumerable.Contains() 表达式?

转载 作者:太空宇宙 更新时间:2023-11-03 11:04:42 25 4
gpt4 key购买 nike

我目前是第一次使用 ASP 动态数据,我正在尝试构建一个过滤器。我们的用户需要根据项目是否是所选父项的子项来定位列表中的项目(我们的项目可以有多个父项)。

有问题的项目是 Segment,每个 Segment 都有一个名为 RouteIds 的属性,类型为 IEnumerable,它是所有 Segment 的父 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 中选择适当的路由,然后我会检查 Segment 的 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.

最佳答案

你的代码有两个问题:

  1. 你的参数是反的。第一个参数必须是集合,第二个参数是您要搜索的项目。
  2. 你的类型参数是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com