c# - 如何使用 System.Linq.Dynamic.Core 将复杂的查询字符串转换为 lambda 表达式

标签 c# asp.net-core .net-core lambda system.linq.dynamic

我有一个像这样的 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(); 
}

结果:

enter image description here

关于c# - 如何使用 System.Linq.Dynamic.Core 将复杂的查询字符串转换为 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65593092/

相关文章:

c# - HTTP 错误 500.19,错误代码为 0x8007000d visual studio 2017,同时部署 .net 核心应用程序

c# - Xamarin:跨平台获取设备信号强度和/或电池生命周期

c# - 以编程方式创建 SQLCE 数据库

asp.net-core - 增加asp.net核心中的最大url长度

.net-core - 如何为.net core 2.0 webapi设置默认日期时间格式

c# - 在 IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware) 中使用委托(delegate)作为 Func 参数的目的是什么

c# - WPF DataGrid CellTemplateSelector 项目

c# - 如何从 Xamarin 中的 Assets 文件夹读取 Json/文本文件

c# - Visual Studio 2017 Docker 支持不适用于 ASP.Net Core Angular 或 React 项目

asp.net - 使用 ASPNet Core 托管在 Linux 上的 Windows 身份验证