Search code examples
c#linqexpression-treesdynamic-linq

System.Linq.Dynamic.DynamicExpression parsing expressions with enum parameters


I am trying to parse a LambdaExpression Tree using DynamicExpression.ParseLambda but I cannot get it to correctly parse when using string.Equals with the StringComparison enum.

I have tried:

a) using StringComparison but I get the error 'Unknown identifier 'StringComparison''.

b) using the full namespace of System.StringComparison but I get the error 'Unknown identifier 'System''.

    [TestMethod()]
    public void CanParseStringEqualsWithEnum()
    {
        var input = @"p0.Equals(""Testing"", StringComparison.InvariantCultureIgnoreCase)";

        var p0 = Expression.Parameter(typeof(string), "p0");

        System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p0 }, typeof(bool), input);
    }

Removing the StringComparison works.

[TestMethod()]
public void CanParseStringEqualsWithEnum()
{
    var input = @"p0.Equals(""Testing"")";

    var p0 = Expression.Parameter(typeof(string), "p0");

    System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p0 }, typeof(bool), input);
}

I could perform .ToUpper() on both strings and compare that way, but I know this doesn't cover all scenarios and it's better to use StringComparison.


Solution

  • Another solution (which does not involve code-changes) is using the value 3 for the enumeration.

    When using System.Linq.Dynamic.Core, the following code works:

    var input = @"p0.Equals(""Testing"", 3)";
    var p0 = Expression.Parameter(typeof(string), "p0");
    var expression = DynamicExpressionParser.ParseLambda(new[] { p0 }, typeof(bool), input);
    Delegate del = expression.Compile();
    var result = del.DynamicInvoke("testing") as bool?;
    

    UPDATE

    I've changed the code for System.Linq.Dynamic.Core (version 1.0.16). Now it's also possible to use:

    var input = @"p0.Equals(""Testing"", StringComparison.InvariantCultureIgnoreCase)";
    // ...