tags:

views:

994

answers:

1

Given a Lambda Expression:

Define(Expression<Func<T, int>> property)

and used like:

Define(x => x.Collection.Count)

What is the best method of getting the value of Count? Is there an easy way with the Expression Tree or should I use reflection to parse the tree to get the PropertyInfo and GetValue()?

+2  A: 

You can use the following to get a delegate corresponding to your lambda:

var propDelegate = property.Compile();
var count = propDelegate(...);

propDelegate will be a Func<T, int>, and you can invoke it by passing in the required object of type T.

Denis Troller
Thanks Denis, that worked. Working code given the original example: var propDelegate = property.Compile(); var count= propDelegate.DynamicInvoke(new object[] { instance } );
TechnoAg