3

我有一个像

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

此表达式作为字符串传递到方法中,因为它来自配置文件。这意味着我必须将字符串转换为表达式才能执行它。

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();
}

如果我只输入"x => x.Property0 == \" Z \""过滤器变量,那么结果很合适,所以问题似乎是旧的。Any,但我还没有找到问题的解决方案。但是,没有抛出错误,因此没有问题的迹象。

谁能告诉我为什么表达式不能正常工作,或者我需要调整什么才能使其工作。

谢谢

4

1 回答 1

2

old是一个变量,你应该传递一个值给它。

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(); 

例子:

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(); 
}

结果:

在此处输入图像描述

于 2021-01-07T03:37:01.430 回答