Note: please pay attention carefully this is not a duplicate.
I need to create the following Lambda expression:
() => model.property
the model and its property will be determine at runtime. I want a function that takes the model and property and generate the expression:
public object GenerateLambda(object model, string property)
{
}
If it is possible I don't want the function to be generic.
but I think the main problem that I have is with () expression.
Update : The return type of GenerateLambda is not important for me right now. Any result that could be replaced instead of ()=>model.property is accepted. The reason that I used object is that I don't know the generic types of properties and they should be dynamic, but as I tested it is possible to cast object to Expression<Func<TValue?>> which is the the final type that I need(TValue is the property type but it will be determined at runtime).
I have created a series of Blazor components that have a property(namely For) of type Expression<Func<TValue?>> which is used to extract custom attribute of models. The way I use this property is by setting it to a Func in this way : () => person.FirstName. Now I need to generate this expression dynamically for each property of the object(model). Suppose that the object and its type themselves are not dynamically created created.
So for each property p in model I want to call GenerateLambda(object model, string property) that should return () => model.p.
pseudo-code:
foreach(propertyInfo p in model){
var result= GenerateLambda(model, p, X or any parameter that is needed);
MyComponent.For= result;
... // other logics
}
objectis not the right return type of the desired functionpublic object GenerateLambda(object model, string property), should bepublic LambdaExpression GenerateLambda(...)? Also provide an example how it will be called and what it will be used for.