Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a model property using a lambda and not a string property name

I'm building a list of properties of a type to include in an export of a collection of that type. I'd like to do this without using strings for property names. Only certain properties of the type are to be included in the list. I'd like to do something like:

exportPropertyList<JobCard>.Add(jc => jc.CompletionDate, "Date of Completion");

How can I go about implementing this generic Add method? BTW, the string is the description of the property.

like image 498
ProfK Avatar asked Aug 24 '10 17:08

ProfK


2 Answers

You can get the PropertyInfo object by examining the Expression passed in. Something like:

public void Add<T>(Expression<Func<T,object>> expression, string displayName)
{
    var memberExpression = expression.Body as MemberExpression;
    PropertyInfo prop = memberExpression.Member as PropertyInfo;
    // Add property here to some collection, etc ? 
}

This is an uncomplete implementation, because I don't know what exactly you want to do with the property - but it does show how to get the PropertyInfo from an Expression - the PropertyInfo object contains all meta data about the property. Also, be sure to add error handling to the above before applying it in production code (ie. guards against the expression not being a MemberExpression, etc.).

like image 118
driis Avatar answered Oct 14 '22 05:10

driis


A superior selector configuration looks like this:

public void MethodConsumingSelector<TContainer, TSelected>(Expression<Func<TContainer, TSelected>> selector)
{
     var memberExpresion = expression.Body as MemberExpression;
     var propertyInfo = memberExpression.Member as PropertyInfo;
}

This prevents the expression being passed in from being a UnaryExpression containing Convert(x => x.ValueTypeProperty) when your selector targets a value type.

See the related question regarding UnaryExpression versus MemberExpression on SO here.

like image 39
Tetsujin no Oni Avatar answered Oct 14 '22 04:10

Tetsujin no Oni