我实际上正在研究一种选择对象的方法,该对象至少有一个属性包含一个或多个单词。
树的构造似乎是正确的,但MethodCall失败了。
以下是代码:
public List<Article> FilterArticle(string expression, ref List<Article> listeArticle)
{
IQueryable<Article> queryableData = listeArticle.AsQueryable();
string[] expressionList = expression.Split(new char[] { ' ' });
Linq.Expression predicate = null;
List<Linq.Expression> predicateList = new List<Linq.Expression>();
int i = 0;
foreach (PropertyInfo property in typeof(Article).GetProperties())
{
foreach (string ex in expressionList)
{
string propertyName = property.Name.ToString();
ParameterExpression parameterEx = Linq.Expression.Parameter(typeof(Article), "objectProperty");
MemberExpression propertyEx = Linq.Expression.Property(parameterEx, propertyName);
MethodInfo toStringMethod = typeof(object).GetMethod("ToString");
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var value = Linq.Expression.Constant(ex, typeof(string));
Linq.Expression containsMethodExp = Linq.Expression.Call(Linq.Expression.Call(propertyEx, toStringMethod), containsMethod, value);
predicateList.Add(containsMethodExp);
if (i == 0) { predicate = predicateList[i]; }
if (i > 0) predicate = Linq.Expression.Or(predicate, predicateList[i]);
i = i + 1;
}
}
Func<IEnumerable<Article>, Func<Article, bool>, IEnumerable<Article>> whereDelegate = Enumerable.Where;
MethodInfo whereMethodInfo = whereDelegate.Method;
// FAIL
MethodCallExpression methodCallEx = Linq.Expression.Call(whereMethodInfo, predicate);
return queryableData.Provider.CreateQuery<Article>(methodCallEx).ToList();
}
这一行:
MethodCallExpression methodCallEx = Linq.Expression.Call(whereMethodInfo, predicate);
发送此错误:
发生了'System.ArgumentException'类型的异常 System.Core.dll但未在用户代码中处理
附加信息:提供的参数数量不正确 打电话给方法 “System.Collections.Generic.IEnumerable1 [Colibri.Models.Article] 其中[文章](System.Collections.Generic.IEnumerable1 [Colibri.Models.Article] System.Func`2 [Colibri.Models.Article,System.Boolean])
谢谢你的帮助。