我有StartsWith
的可行代码,但我需要使用Compare
代替StartsWith
:
LambdaExpression startsWithLambda = (Expression<Func<string, string, bool>>)((x, s) => x.StartsWith(s)); // works
// LambdaExpression startsWithLambda = (Expression<Func<string, string, bool>>)((x, s) => string.Compare(x,s) > 0); - doesn't work
MethodInfo startsWithMI = (startsWithLambda.Body as MethodCallExpression).Method;
ParameterExpression param = Expression.Parameter(typeof(T));
Expression nameProp = Expression.Property(param, _propertyName);
Expression filteredOk = Expression.Constant(true);
Expression startsWithStringExpr = Expression.Constant(_filter);
Expression startsWithCondition = Expression.Call(nameProp, startsWithMI, startsWithStringExpr);
filteredOk = Expression.AndAlso(filteredOk, startsWithCondition);
Expression<Func<T, bool>> where = Expression.Lambda<Func<T, bool>>(filteredOk, new ParameterExpression[] { param });
var result = orderedQuery.Where(where).Take(_linesCount);
如何使用lambda表达式实现string.Compare
?
答案 0 :(得分:0)
找到解决方案: 表达startsWithCondition = Expression.Call(startsWithMI,nameProp,startsWithStringExpr);
如果在Call方法中使用静态方法参数应该切换。