2017-01-27 122 views
0

我有StartsWith一個可行的代碼,但我需要使用Compare而不是StartsWithLambda表達式比較字符串

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); 

如何實現string.Compare與lambda表達式?

回答

0

找到解決方案: 表達式startsWithCondition = Expression.Call(startsWithMI,nameProp,startsWithStringExpr);

如果在Call方法中使用靜態方法參數應該被切換。