动态对象上的 C# 动态表达式

C# Dynamic expression on dynamic object

让我们假设以下场景:

我有两个类:

public class Customer
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


public class Employee
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

然后我可以拥有:

List<Customer> customers = new List<Customer>();

List<Employee> employees = new List<Employee>();

现在我可以这样了:

public static List<Employee> GetMajorEmployees(this List<Employee> employees)
{
    return employees.Where(t=>t.Age >= 18).ToList();
}

但是,如果不在代码中 运行 查询,让用户在服务器端 UI 和 运行 中定义它,就像这样:

 public static List<T> RunCustomQuery<T>(this List<T> items, dynamic query)
{
    return items.ExecuteQuery(query); // to be implemented
}

其中 query 是用户在 UI 中构建并保存在数据库中的实际表达式。

如何在列表上构建动态表达式,并将其作为文本或 json 或 xml 保存到数据库?

在UI上用户可以select/build查询。对于客户列表,查询可以是这样的:

customers.Where(t=>t.FirstName == "Jhon");

我还希望能够自动从动态对象中提取属性,如您所见,这两个 类 具有相同的属性,但也有一些不同的属性。

有人能给我指出正确的方向吗?

我需要的是类似 TFS 的东西:

您可以使用 Expression。它允许您将表达式树放在一起并编译它,然后您可以在任何使用 lambda 的地方将 if 作为 FuncAction 使用。

或者,如果您不编译它,您可以用任何其他方式解释或检查它。

有一些开源项目可以让您序列化和反序列化表达式,但是我没有使用过,所以无法提出建议。