如何使用Expression.Call使用linq扩展方法

时间:2020-08-24 21:58:19

标签: c# linq lambda expression

这是我面临的一个简单例子:

            Expression<Func<Company, bool>> func = a => a.Name == "foo bar";
            var exp = Expression.Call(typeof(IQueryable<Company>), "Where",
                new[] { typeof(Company) }, func);

运行此代码时,我收到以下消息:

No generic method 'Where' on type 'System.Linq.IQueryable`1[BBM.Domain.Entities.Core.Company]' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. 

我不确定为什么会这样。

1 个答案:

答案 0 :(得分:0)

Where实际上是类型System.Linq.Queryable的扩展方法。获得它的最简单方法(由于Queryable具有2个重载,而这些重载仅在谓词Expression<>中的泛型参数数量上有所不同),我想说的只是使用另一个表达式:

Expression<Func<IQueryable<int>, IQueryable<int>>> expr = x => x.Where(y => true);
var mi = ((MethodCallExpression)expr.Body).Method;

但是我想说您似乎实际上不需要这样做,因为您可以手动创建Call表达式:

Expression<Func<Company, bool>> func = a => a.Name == "foo bar";
Expression<Func<IQueryable<Company>, IQueryable<Company>>> call = x => x.Where(func);