0

I have a series of objects that all have a similar property that is a List of the Ids of the groups to which they belong (many parents per child).

I'm having trouble programatically implementing the Linq Expression necessary to make this filter work correctly.

This is what I have so far:

IQueryable result = null;

   if (!string.IsNullOrWhiteSpace(this.ddlRouteNames.SelectedValue))
   {
      ConstantExpression ce = Expression.Constant(int.Parse(this.ddlRouteNames.SelectedValue));
      ParameterExpression pe = Expression.Parameter(source.ElementType);
      MemberExpression me = Expression.Property(pe, this.Column.Name);
      MethodCallExpression mce = Expression.Call(typeof(List<int>), "Contains", new[] { typeof(int) }, me, ce);

      result = source.Provider.CreateQuery(mce);
   }

return result;

I'm getting an exception when trying to create my MethodCallExpression:

No method 'Contains' exists on type 'System.Collections.Generic.List`1[System.Int32]'.

Any pointers on where to begin?

4

2 回答 2

0

您的方法调用不正确,要调用非静态方法,您需要提供包含该方法的实例。这是Contains方法调用的示例:

var list = new List<int> {1};
//Target for invoke method
var target = Expression.Constant(list);
var methodCallExpression = Expression.Call(target, typeof(List<int>).GetMethod("Contains"), Expression.Constant(1));

如果在您的代码中me它是包含List代码的成员,则如下所示:

Expression.Call(me, typeof(List<int>).GetMethod("Contains"), ce);
于 2013-05-07T15:49:10.930 回答
0

Type您使用的方法签名中:

public static MethodCallExpression Call(Type type, 
                                        string methodName, 
                                        Type[] typeArguments, 
                                        params Expression[] arguments);

指定包含特定静态方法的类型。

您需要此方法的类型实例可用 - 一个示例(与您的评论相关):

var par = Expression.Parameter(typeof(int), "par");            
var inst = Expression.Parameter(typeof(List<int>), "inst");
var body = Expression.Call(inst, typeof(List<int>).GetMethod("Contains"), par);
var exp = Expression.Lambda(body, inst, par);
var deleg = exp.Compile();

var lst = new List<int>() { 1, 2, 3, 4, 5 };
var exists = deleg.DynamicInvoke(lst, 3);
于 2013-05-07T15:44:12.273 回答