Select a model property using lambda name rather than row name

I am creating a list of type properties to include in the export of a collection of this type. I would like to do this without using strings for property names. Only certain properties of this type should be included in the list. I would like to do something like:

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

How can I implement this general Add method? BTW, a string is a description of a property.

+8
generics lambda linq
Aug 24 '10 at 17:02
source share
2 answers

You can get the PropertyInfo object by looking at the passed expression. 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 incomplete implementation, because I don’t know what exactly you want to do with this property, but it shows how to get PropertyInfo from an expression - the PropertyInfo object contains all the metadata about this property. Also, be sure to add the error handling above before applying it in production code (i.e. Protect from an expression other than MemberExpression, etc.).

+9
Aug 24 '10 at 17:09
source share

An excellent selector configuration is as follows:

 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 from being passed from UnaryExpression containing Convert(x => x.ValueTypeProperty) when your selector is targeting a value type.

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

0
Jul 21 '14 at 21:27
source share



All Articles