How can I convert a property name to Lambda expression in C#?
Like this: string prop = "Name";
to (p => p.Name
)
public class Person{
public string Name{ get; set; }
}
Thanks!
Using expression trees you can generate the lambda expression.
using System.Linq.Expressions;
public static Expression<Func<T, object>> GetPropertySelector<T>(string propertyName)
{
var arg = Expression.Parameter(typeof(T), "x");
var property = Expression.Property(arg, propertyName);
//return the property as object
var conv = Expression.Convert(property, typeof(object));
var exp = Expression.Lambda<Func<T, object>>(conv, new ParameterExpression[] { arg });
return exp;
}
for Person
you can call it like:
var exp = GetPropertySelector<Person>("Name");//exp: x=>x.Name
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments