【问题标题】:How to build a LINQ expression with Contains method from IEnumerable?如何使用 IEnumerable 中的 Contains 方法构建 LINQ 表达式?
【发布时间】: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 =&gt; 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


【解决方案1】:

在我看来,你只是把论点弄错了。

这个:

Expression.Call(method, property, value)

表示您正在调用:

Enumerable.Contains(x.Col_id, ids)

你想要的

Enumerable.Contains(ids, x.Col_id)

那就试试吧:

var containsMethod = Expression.Call(method, value, property);

编辑:接下来,我认为您正在构建错误的 Contains 类型参数。我怀疑你想要:

MethodInfo method = typeof(Enumerable).
                    GetMethods().
                    Where(x => x.Name == "Contains").
                    Single(x => x.GetParameters().Length == 2).
                    MakeGenericMethod(typeof(int));

毕竟,你想打电话给Enumerable.Contains&lt;int&gt;,而不是Enumerable.Contains&lt;SomeType&gt;

【讨论】:

  • 我也试过了:Expression of type 'System.Collections.Generic.IEnumerable'1[System.Int32]' cannot be used for type parameter 'System.Collections.Generic.IEnumerable'1[T] from 'Boolean Contains[T](System.Collections.Generic.IEnumerable'1[T], T)' method.
  • @Shin:啊,是的 - 你的MakeGenericMethod(typeof(TEntidad) 也不正确正在编辑中。
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
相关资源
最近更新 更多