title: EF Dynamic Field Select using LINQ
body: <p>I have the following select:</p>
  
  <pre><code>var sortedCodes = Codes
  .Where(c =&gt; c.Active)
  .OrderByDescending(x =&gt; x.SortOrder)
  .Select(b =&gt; new { b.Display, b.NumericCode, b.SortOrder })
  .Distinct()
  .ToList();
  </code></pre>
  
  <p>The table Code has many columns such as NumericCode, TextCode, AlphaCode, ThreeCode, FourCode, FiveCode. I am using this table to build selects in my UI. Is there a way I can create some dynamic code so I can pass in the column name to use for the value?</p>
  
  <p>The above select would look like this:</p>
  
  <pre><code>.Select(b =&gt; new { b.Display, "TextCode", b.SortOrder })
  </code></pre>
  
  <p>I was thinking I could use an Expression, but I do not think this is exactly what I need as it is actually printing the lambda as the value.</p>
  
  <pre><code>var arg = Expression.Parameter(typeof(Code), "b");
  var body = Expression.Property(arg, valueColumn);
  var lambda = Expression.Lambda&lt;Func&lt;Code, string&gt;&gt;(body, arg);
  
  var sortedCodes = Codes
  .Where(c =&gt; c.Active)
  .OrderByDescending(x =&gt; x.SortOrder)
  .Select(b =&gt; new { b.Display, Value=lambda, b.SortOrder })
  .Distinct()
  .ToList();
  </code></pre>