title: Convert string to lambda expression to pass to LINQ Select
body: <p>This is the string i want to convert into lambda expression</p>
  
  <pre><code>"o =&gt; new { Division = o.Division, Department = o.Department }"
  </code></pre>
  
  <p>Actually, I want to create a select lambda expression of anonymous type.</p>
  
  <p>I am able to get this expression:</p>
  
  <pre><code>o =&gt; new SystemViewModel { Division = o.Division, Department = o.Department } 
  </code></pre>
  
  <p>but I want this expression </p>
  
  <pre><code>o =&gt; new { Division = o.Division, Department = o.Department}
  </code></pre>
  
  <p>This is the code </p>
  
  <pre><code>var dte = ctx.Database.SqlQuery&lt;SystemViewModel&gt;("select distinct Division,Department from TestReportView").ToList();"
  
  var result2 = dte.Select(CreateNewStatement(string.Join(",", "Division,Department"))).ToList();
  
  Func&lt;SystemViewModel, SystemViewModel&gt; CreateNewStatement(string fields)
  {
      // input parameter "o"
      var xParameter = Expression.Parameter(typeof(SystemViewModel), "o");
  
      // new statement "new Data()"
      var xNew = Expression.New(typeof(SystemViewModel));
  
      // create initializers
      var bindings = fields.Split(',').Select(o =&gt; o.Trim())
          .Select(o =&gt; {
  
      // property "Field1"
      var mi = typeof(SystemViewModel).GetProperty(o);
  
      // original value "o.Field1"
      var xOriginal = Expression.Property(xParameter, mi);
  
      // set value "Field1 = o.Field1"
      return Expression.Bind(mi, xOriginal);
          }
      );
  
      // initialization "new Data { Field1 = o.Field1, Field2 = o.Field2 }"
      var xInit = Expression.MemberInit(xNew, bindings);
  
      // expression "o =&gt; new Data { Field1 = o.Field1, Field2 = o.Field2 }"
      Type anonType = new { Name = "abc", Num = 123 }.GetType();
      var lambda = Expression.Lambda&lt;Func&lt;SystemViewModel, SystemViewModel&gt;&gt;(xInit, xParameter);
      var e = lambda.Body.ToString();
      //LambdaExpression.
      // compile to Func&lt;Data, Data&gt;
      return lambda.Compile();
  }
  </code></pre>
  
  <p>This returns a list of <code>SystemViewModel</code> but I want a list of anonymous types, with only the two dynamic field Division and Department (<code>SystemViewModel</code> contains many other fields).</p>