Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate a lambda expression

Tags:

lambda

linq

I have a class

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
}

And I have a lambda expression of the Person type

Expression<Func<TModel, TProperty>> expression

Who contains this value

{model => model.Name}

How can I evaluate that lambda expression against an instance of Person, to extract the Name value attribute?

like image 321
iuristona Avatar asked Apr 09 '26 08:04

iuristona


1 Answers

You can compile the expression into a delegate and pass in a Person object:

Func<Person, string> getName = expression.Compile();
string name = getName(person);
like image 195
Mark Cidade Avatar answered Apr 11 '26 22:04

Mark Cidade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!