Search code examples
c#expressionexpression-trees

C# Dynamic expression on dynamic object


Let's assume the following scenario:

I have two classes:

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

and then I can have:

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

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

Now I can have like this:

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

But what about instead of running the query in the code, have the user define it in the UI and run it in the server side like this:

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

Where query is the actual expression built in the UI by the user and saved in the database.

How can I build a dynamic expression on the lists, and save it to database as text or json or xml?

On the UI the user can select/build the query. For list of customers the query can be something like:

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

Also I want to be able to pull the properties automatically from the dynamic object, as you can see the two classes have same properties but also some different ones.

Can somebody point me to the right direction?

What I need is something like TFS has:

enter image description here


Solution

  • You can use Expression for that. It allows you to put together an expression tree and compile it and then you can use if as a Func or Action anywhere where you use lambdas.

    Or if you do not compile it you can interpret it or inspect in any other way.

    There are some open source projects that allow you to serialise and deserialise Expressions however I have not used any so cannot make recommendations.