Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...