Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property Name to Lambda Expression C#

Tags:

c#

lambda

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!

like image 368
Renan Araújo Avatar asked Aug 11 '15 17:08

Renan Araújo


2 Answers

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
like image 174
Taher Rahgooy Avatar answered Nov 19 '22 23:11

Taher Rahgooy


A lambda is just an anonymous function. You can store lambdas in delegates just like regular methods. I suggest you try making "Name" a property.

public string Name { get { return p.Name; } }

If you really want a lambda, use a delegate type such as Func.

public Func<string> Name = () => p.Name;

like image 31
Philippe Paré Avatar answered Nov 20 '22 00:11

Philippe Paré