我有一个可行的代码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
?
找到了解决方案: 表达式 startsWithCondition = Expression.Call(startsWithMI, nameProp, startsWithStringExpr);
如果在调用方法中使用静态方法参数,则应切换。