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

c# dynamic-linq expression-trees linq

Question

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.

1
1
6/5/2019 10:20:42 AM

Accepted Answer

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)";
// ...
1
6/6/2019 12:02:34 PM

Popular Answer

Found this answer and went with patching the sources for the System.Linq.Dynamic library. Downloaded the package sources from GitHub and added System.StringComparison to the "predefinedTypes" array of Types within System.ExpressionParser.

UPDATE: See Stef's answer for a better solution: https://stackoverflow.com/a/56472200/785965



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow