C#表达式类方法扩展,使字符串比较不区分大小写

时间:2018-01-07 19:31:29

标签: c# linq expression string-comparison

这是我的Expression扩展方法,可将InBetweenStr功能添加到ExpressionSystem.Linq.Expressions.Expression)类。但是,我想暗示字符串比较忽略大小写,所以我修改了StringComparisonExpression并添加了第三个参数:StringComparison.CurrentCultureIgnoreCase。但当然代码不起作用并抛出一个异常,说:“为调用方法Int32 Compare(System.String, System.String, System.StringComparison)提供的参数数量不正确”。

所以我想知道除了从StringComparison.CurrentCultureIgnoreCase

string.Compare作为第三个参数传递给Expression.Call之外,还有一种优雅的方法可以使字符串比较不区分大小写

代码:

// for InBetweenStr and NotInBetweenStr
public static Expression<Func<int>> StringComparisonExpression = () => string.Compare(null, null);
public static MethodInfo StringComparisonExpressionhMethodInfo = ((MethodCallExpression) StringComparisonExpression.Body).Method;


public static Expression InBetweenStr(this Expression value, Expression lowerBound, Expression upperBound)
{
    // zero constant expression
    var zeroExpr = Expression.Constant(0);

    return Expression.AndAlso(
        Expression.GreaterThanOrEqual(Expression.Call(StringComparisonExpressionhMethodInfo, value, lowerBound), zeroExpr),
        Expression.LessThanOrEqual(Expression.Call(StringComparisonExpressionhMethodInfo, value, upperBound), zeroExpr)
    );
}

修改后的StringComparisonExpression导致异常:

public static Expression<Func<int>> StringComparisonExpression = () => string.Compare(null, null, StringComparison.CurrentCultureIgnoreCase);

1 个答案:

答案 0 :(得分:3)

您可以获得MethodInfo三参数string.Compare方法,如下所示:

private static readonly MethodInfo StringComparisonExpressionMethodInfo =
    typeof(string).GetMethod("Compare", new Type[] {
        typeof(string), typeof(string), typeof(StringComparison)
    });

使用此MethodInfo,您可以使用第三个参数调用该方法:

var ignoreCase = Expression.Constant(StringComparison.CurrentCultureIgnoreCase);
return Expression.AndAlso(
    Expression.GreaterThanOrEqual(Expression.Call(StringComparisonExpressionMethodInfo, value, lowerBound, ignoreCase), zeroExpr),
    Expression.LessThanOrEqual(Expression.Call(StringComparisonExpressionMethodInfo, value, upperBound, ignoreCase), zeroExpr)
);

由于您为第三个参数传递常量,因此使ignoreCase常量表达式与您zeroExpr的方式相同。