Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Expression class method extension, making string comparison case insensitive

This is my Expression extension method that adds InBetweenStr functionality to Expression (System.Linq.Expressions.Expression) class. However, I want to imply to string comparison to ignore case so I modified StringComparisonExpression and added third argument: StringComparison.CurrentCultureIgnoreCase. But of course code does not work and throws an exception saying that: "Incorrect number of arguments supplied for call to method Int32 Compare(System.String, System.String, System.StringComparison)".

So I am wondering is there an elegant way to make string comparison case insensitive other than passing StringComparison.CurrentCultureIgnoreCase as a third argument to string.Compare from Expression.Call

Code:

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

Modified StringComparisonExpression which results in exception:

public static Expression<Func<int>> StringComparisonExpression = () => string.Compare(null, null, StringComparison.CurrentCultureIgnoreCase);
like image 530
Node.JS Avatar asked Apr 20 '26 21:04

Node.JS


1 Answers

You can get MethodInfo of the three-argument string.Compare method like this:

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

With this MethodInfo in place you can call the method with a third parameter:

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

Since you are passing a constant for the third parameter, make ignoreCase constant expression the same way you made zeroExpr.

like image 93
Sergey Kalinichenko Avatar answered Apr 22 '26 18:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!