0
我有StartsWith
一個可行的代碼,但我需要使用Compare
而不是StartsWith
:Lambda表達式比較字符串
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表達式?