Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I create a dynamic multi-property Select on an IEnumerable<T> at runtime?
    primarykey
    data
    text
    <p>I asked a <a href="https://stackoverflow.com/questions/8990231/how-can-i-create-a-dynamic-select-on-an-ienumerablet-at-runtime">very similar question</a> yesterday, but it wasn't until today I realised the answer I accepted doesn't solve all my problems. I have the following code:</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>Which is used as follows:</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> <p>This allows me to pull out the primary keys from an <code>IQueryable&lt;TUnknown&gt;</code>. The problem is that this code only works with a single primary key and I need to add support for multiple PKs. </p> <p>So, is there any way I can adapt the <code>SelectExpression</code> method above to take an <code>IEnumerable&lt;string&gt;</code> (which is my list of primary key property names) and have the method return an expression that selects those keys?</p> <p>I.e. Given the following: </p> <pre><code>var knownRuntimePrimaryKeys = new string[] { "CustomerId", "OrderId" }` </code></pre> <p>My Select needs to do the following (at runtime):</p> <pre><code>var primaryKeys = query.Select(x=&gt; new { x.CustomerId, x.OrderId }); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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