I'm new to expressions, and i'd like to know how if it's in any way possible to convert my expression
Let's say in this example my TModel is of type Customer, and assigned it somewhere like this:
Expression<Func<TModel, string>> getvalueexpression = customer =>customer.Name
to something like
Expression<Action<TModel,string>> setvalueexpression = [PSEUDOCODE] getvalueexpression = input
Action<TModel,string> Setter = setvalueexpression.Compile();
Setter(mycustomer,value);
So in short, i want to somehow build and compile an expression that sets the customer name specified by my getter expression, to a specific value.
As the correct answer didn't work for me (collections in the expression) but pushed me to the right direction, I needed to investigate this a lot and I think I came up with a method which can generate setter for literally any member expression.
For properties and fields it behaves the same as the marked answer (I believe it is much more transparent though).
It has additional support for Lists and Dictionaries - please see in the comments.
I have this helper method which returns the property info for a property:
Usage:
GetPropertyInfo((MyClass c) => c.PropertyName);
You can then use the PropertyInfo to set the value of the property on a class.
You will need to modify the code to suit your needs but hopefully it will help.
this is my way
Modified version. This class is probably better than many other ones you can find around :-) This is because this version support direct properties (
p => p.B
) (as everyone else :-) ), nested properties (p => p.B.C.D
), fields (both "terminal" and "in the middle", so inp => p.B.C.D
bothB
andD
could be fields) and "inner" casting of types (sop => ((BType)p.B).C.D
andp => (p.B as BType).C.D)
. The only thing that isn't supported is casting of the "terminal" element (so nop => (object)p.B
).There are two "codepaths" in the generator: for simple Expressions (
p => p.B
) and for "nested" expressions. There are code variants for .NET 4.0 (that has theExpression.Assign
expression type). From some benchmarks of mine the fastest delegates are: "simple"Delegate.CreateDelegate
for properties,Expression.Assign
for fields and "simple"FieldSetter
for fields (this one is just a little slower thanExpression.Assign
for fields). So under .NET 4.0 you should take away all the code marked as 3.5.Part of the code isn't mine. The initial (simple) version was based on the Fluent NHibernate code (but it supported only direct properties), some other parts are based on code from How do I set a field value in an C# Expression tree? and Assignment in .NET 3.5 expression trees.