title: Using Lambda Expression to Select different fields from field names
body: <p>I need to get two fields from a database table (retrieved using linq-to-sql), one field is a datetime (and is a fixed field) and the other is always a decimal, but the field can be different.</p>
  
  <p>The table holds currency data which is processed twice a day and in different currencies so could have fields such as AM_USD, PM_USD, AM_EUR etc. And I need to get data such as a list of the date against PM_USD or the date against AM_EUR.</p>
  
  <p>I would like to be able to call the data using a lambda expression for example (this is a stripped out example):</p>
  
  <pre><code>data = TableData.Select(x=&gt;new {x.DateTimeAdded, x.[**field name as string**]});
  </code></pre>
  
  <p>I have been trying to write a function to do this, and am failing dismally.</p>
  
  <p>The closest I have managed is:</p>
  
  <pre><code>private Func&lt;TableData, KeyValuePair&lt;DateTime, decimal&gt;&gt; CreateSelect(string FieldName)
  {
      var parameterExp = Expression.Parameter(typeof(TableData), "sel");
      var dateParameter = Expression.Parameter(typeof(DateTime), "DateTimeAdded");
      var fieldParameter = Expression.Parameter(typeof(decimal), FieldName);
      ConstructorInfo constructorInfo = typeof(KeyValuePair&lt;DateTime, decimal&gt;).GetConstructor(new[] { typeof(DateTime), typeof(decimal) });
      NewExpression constructExpression = Expression.New(constructorInfo, new ParameterExpression[] { dateParameter, fieldParameter});
  
      var lambda = Expression.Lambda&lt;Func&lt;TableData, KeyValuePair&lt;DateTime, decimal&gt;&gt;&gt;( constructExpression, parameterExp);
  
      return lambda.Compile();
  }
  </code></pre>
  
  <p>Which fails with "System.InvalidOperationException: Lambda Parameter not in scope".</p>
  
  <p>I'm sure I missing something obvious, or going about it wrong way.</p>
  
  <p>Any ideas?</p>
  
  <p>Thanks
  T</p>