我有一个像这样的 lambda 表达式
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();
}
如果我只在filter变量中输入"x => x.Property0 ==\"Z\""
,那么结果就符合了,所以问题好像是老Any,但我还没有找到解决问题的办法。但是,不会引发任何错误,因此没有任何问题的迹象。
谁能告诉我为什么表达式不能正常工作,或者我需要调整什么才能使其工作。
谢谢
最佳答案
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();
}
结果:
关于c# - 如何使用 System.Linq.Dynamic.Core 将复杂的查询字符串转换为 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65593092/