Dynamically creating an expression which selects an objects property
<p>I want to be able to build up an expression dynamically, which is essentially a property selector.</p>

<p>I am trying to use this so I can provide a flexible search UI and then translate the selected search parameters to an Entity Framework query.</p>

<p>I have most of what I need thanks to another library I am using, but am missing the final part which translates my query string parameters to the appropriate expression selector the other library requires.</p>

<p>The library takes an argument of : </p>

<pre><code>Expression&lt;Func&lt;TObject, TPropertyType&gt;&gt;
</code></pre>

<p>An example of how this would be coded if baked into an application would be :</p>

<pre><code>Expression&lt;Func&lt;MyObject, int&gt;&gt; expression = x=&gt; x.IntegerProperty;
</code></pre>

<p>However, I need to be able to generate this expression dynamically, as the important point is that all I will know is the type of object (MyObject) and the property name as a string value ("IntegerProperty"). The property value will obviously map to an property on the object which could be of any non complex type.</p>

<p>So essentially I think I am wanting to find a way to build up the expression dynamically which specifies the correct object property to return and where the return value is determined by that property type.</p>

<p>psuedo code : </p>

<pre><code>string ObjectPropertyName
Type ObjectType
Type ObjectPropertyType = typeof(ObjectType).GetProperty(ObjectPropertyName).Property

 Expression&lt;Func&lt;[ObjectType], [ObjectPropertyType]&gt;&gt; expression = x=&gt; x.[ObjectPropertyName];
</code></pre>

<p>Update :</p>

<p>I have got as far as this </p>

<pre><code>ParameterExpression objectParameter = Expression.Parameter(type, "x");
MemberExpression objectProperty = Expression.Property(objectParameter, "PropertyNameString");
Expression&lt;Func&lt;ObjectType, int&gt;&gt; expression = Expression.Lambda&lt;Func&lt;ObjectType, int&gt;&gt;(objectProperty, objectParameter);
</code></pre>

<p>But the problem I have with this is that the return type is not always an int but may be some other type.</p>