Search code examples
c#lambdaexpression-trees

Multiple assignment operations in one lambda expression


I am trying to create a dynamic lambda expression (parsed from text), that does more than one assignment. Creating the individual assignments was fairly easy, however I am stuck on how to combine them. So what I'm trying to achieve is the same as:

Action<Entity> action = (entity) => 
{ 
    entity.Property1 = "1"; 
    entity.Property2 = "2";
};

Is there a way to combine more than one Expression.Assign expressions into one (since Expression.Lambda only takes one Expression as input)?

--Edit: So for clarification the code I wrote was just pseudo-code, so the typo (now corrected) doesn't change anything. The code I have right now is something like :

Expression parameter = Expression.Parameter(typeof(Entity), "param");
Expression firstProperty = Expression.Property(parameter, "Property1");
Expression first = Expression.Assign(firstProperty, "1");
Expression secondProperty = Expression.Property(parameter, "Property2");
Expression second = Expression.Assign(secondProperty, "2");
Expression final = [INSERT MAGIC HERE]
Action<Entity> action = Expression.Lambda<Action<Entity>>(final, entity).Complie();

Note that the property name actually come from text input, and the number of assigment expressions isn't limited to 2, it's just for demonstration purposes. My question is, is there an expression the lets me combine the assigment expressions or do I have to create different lambdas for each one?


Solution

  • Try this magic:

    Expression.Block(first, second);