3

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

mj1313
  • 7,930
  • 2
  • 12
  • 32
acridMusak
  • 45
  • 1
  • 4
  • For starters, break a debugger after `exp` is assigned, and look at its `DebugView` property (you can only inspect this from a debugger). [edit] your question to include the value that it contains -- that shows you what the expression actually contains – canton7 Jan 06 '21 at 09:23
  • Also, it's not clear what your actual problem is. What does "is not working correctly" mean? – canton7 Jan 06 '21 at 09:24

1 Answers1

2

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

mj1313
  • 7,930
  • 2
  • 12
  • 32