how convert a complex query string to lambda expression with System.Linq.Dynamic.Core

2.1k Views Asked by At

I have a lambda expression like

x => x.Property0 == "Z" && old.Any(y => y.Key0 == x.Key0 && y.Property0 != x.Property0)

This expression is passed into the method as a string because it comes from a configuration file. That means I have to convert the string into an expression in order to then execute it.

public override async Task<IList<T>> CalculateList<T>(IList<T> old, IList<T> current)
{
    string filter = "x => x.Property0 == \"Z\" && old.Any(y => y.Key0 == x.Key0 && y.Property0 != x.Property0)";

    var exp = DynamicExpressionParser.ParseLambda<T, bool>(ParsingConfig.Default, false, filter, new object[0]);

    var func = exp.Compile();

    return current.Where(func).ToList();
}

If I only enter "x => x.Property0 == \" Z \"" in the filter variable, then the result fits, so the problem seems to be the old.Any, but I have not yet found a solution to the problem . However, no error is thrown, so no indication of the problem.

Can anyone tell me why the expression is not working correctly, or what I need to adjust to make it work.

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

old is a variable, you should pass a value to it.

string filter = "x => x.Property0 == \"AA\" && @0.Any(y => y.Key0 == x.Key0 && y.Property0 != x.Property0 )";
var exp = DynamicExpressionParser.ParseLambda<T, bool>(ParsingConfig.Default, false, filter, old);
var func = exp.Compile();

return current.Where(func).ToList(); 

Example:

public async Task<IActionResult> IndexAsync()
{
    IList<Employee> current = new List<Employee>
    {
        new Employee{ Id = 1, Name = "AA"},
        new Employee{ Id = 2, Name = "BB"},
        new Employee{ Id = 3, Name = "CC"},
        new Employee{ Id = 4, Name = "DD"},
    };
    IList<Employee> old = new List<Employee>
    {
        new Employee{ Id = 1, Name = "BB"},
        new Employee{ Id = 2, Name = "AA"},
        new Employee{ Id = 4, Name = "DD"},
    };

    var result = CalculateList(old, current);
    
    return View();
}

public IList<T> CalculateList<T>(IList<T> old, IList<T> current)
{

    string filter = "x => x.Name == \"AA\" && @0.Any(y => y.Id == x.Id && y.Name != x.Name)";
    var exp = DynamicExpressionParser.ParseLambda<T, bool>(ParsingConfig.Default, false, filter, old);
    var func = exp.Compile();

    return current.Where(func).ToList(); 
}

Result:

enter image description here