I'm trying to generate a "Property Selector" from a string.
Let me explain myself a bit with a Real life example:
We have a Person class with a Name (string) property.
I could manually create a "property selector" like this propertySelector writing:
Expression<Func<Person, string>> propertySelector = x => x.Name;
But I would like to get the same property selector with my method.
var propertySelector = CreatePropertySelectorExpression<Person, string>("Name");
What I have so far is this:
public static Expression<Func<TIn, TOut>> CreatePropertySelectorExpression<TIn, TOut>(string path)
{
Expression exp = Expression.Parameter(typeof(TIn), "x");
foreach (var property in path.Split('.'))
{
exp = Expression.PropertyOrField(exp, property);
}
return exp;
}
But... I've got and invalid cast error!
Cannot implicitly convert type 'System.Linq.Expressions.Expression' to 'System.Linq.Expressions.Expression>'. An explicit conversion exists (are you missing a cast?)
I'm very new to Expressions and I don't know how to continue :(
Your exp
only contains the body of the lambda. But you want an actual lambda function that takes a parameter of type TIn
there. So you need to create a lambda using Expression.Lambda
:
var param = Expression.Parameter(typeof(TIn));
var body = Expression.PropertyOrField(param, propertyName);
return Expression.Lambda<Func<TIn, TOut>>(body, param);
Note though that the expression does not really help you much. You probably want a compiled function instead:
private static Func<TIn, TOut> CreatePropertyAccessor<TIn, TOut> (string propertyName)
{
var param = Expression.Parameter(typeof(TIn));
var body = Expression.PropertyOrField(param, propertyName);
return Expression.Lambda<Func<TIn, TOut>>(body, param).Compile();
}
You can then use it like this:
var name1 = CreatePropertyAccessor<Obj, string>("Name");
var name2 = CreatePropertyAccessor<Obj, string>("Name2");
var name3 = CreatePropertyAccessor<Obj, string>("Name3");
var o = new Obj() // Obj is a type with those three properties
{
Name = "foo",
Name2 = "bar",
Name3 = "baz"
};
Console.WriteLine(name1(o)); // "foo"
Console.WriteLine(name2(o)); // "bar"
Console.WriteLine(name3(o)); // "baz"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With