Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I create a dynamic Select on an IEnumerable<T> at runtime?
    text
    copied!<p>Given that I have an <code>IEnumerable&lt;T&gt;</code>, where <code>T</code> is any object, how can I select a specific property from it, given that I know the name of the one of the property names at run time as a string?</p> <p>For example:</p> <pre><code>var externalIEnumerable = DataPassedFromConsumingCode(); // `IEnumerable&lt;T&gt;` string knownPropertyName = "Foo"; var fooSelect = externalIEnumerable.Select(...); </code></pre> <p>In essence, I'm obviously just doing <code>externalIEnumerable.Select(x=&gt; x.Foo);</code>, but I need to perform this <code>Select</code> at runtime, when I don't have control over when it's initially created.</p> <p>-- </p> <p><strong>ANSWER:</strong> Based on AlanT's answer, here's what I actually did:</p> <pre><code>public Expression&lt;Func&lt;TItem, object&gt;&gt; SelectExpression&lt;TItem&gt;(string fieldName) { var param = Expression.Parameter(typeof(TItem), "item"); var field = Expression.Property(param, fieldName); return Expression.Lambda&lt;Func&lt;TItem, object&gt;&gt;(field, new ParameterExpression[] { param }); } </code></pre> <p>I kept it as an Expression, because calling <code>Compile</code> caused the IQueryable to be Enumerated, which meant the database was hit unnecessarily. So, to use it, I just do the following:</p> <pre><code>string primaryKey = _map.GetPrimaryKeys(typeof(TOriginator)).Single(); var primaryKeyExpression = SelectExpression&lt;TOriginator&gt;(primaryKey); var primaryKeyResults = query.Select(primaryKeyExpression).ToList(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload