title: Call a method in an expression tree lambda
body: <p>I am trying to emulate this lambda call with expression trees:</p>
  
  <pre><code>myList.AsQueryable().GroupBy(g=&gt;g.Name).Select(s =&gt; s.FirstOrDefault());
  </code></pre>
  
  <p>So far i got myself here:</p>
  
  <pre><code>public Expression Distinct (IQueryable queryable, string propertyName)
  {
      var propInfo = queryable.ElementType.GetProperty(propertyName);
      var collectionType = queryable.ElementType;
  
      var groupParameterExpression = Expression.Parameter(collectionType, "g");
      var propertyAccess = Expression.MakeMemberAccess(groupParameterExpression, propInfo);
      var groupLambda = Expression.Lambda(propertyAccess, groupParameterExpression);
      var groupExpression = Expression.Call(typeof(Queryable), "GroupBy", new Type[] { collectionType, propInfo.PropertyType }, queryable.Expression, groupLambda);
  
      var selectParameterExpression = Expression.Parameter(groupExpression.Type, "s");
      var selectFirstOrDefaultMethodExpression = Expression.Call(typeof(Enumerable), "FirstOrDefault", new Type[] { collectionType }, selectParameterExpression);
      var selectLambda = Expression.Lambda(selectFirstOrDefaultMethodExpression, selectParameterExpression);
      return Expression.Call(typeof(Queryable), "Select", new Type[] { groupExpression.Type, selectParameterExpression.Type }, groupExpression, selectLambda);
  }
  </code></pre>
  
  <p>This part passess okay:</p>
  
  <pre><code>var groupParameterExpression = Expression.Parameter(collectionType, "g");
  var propertyAccess = Expression.MakeMemberAccess(groupParameterExpression, propInfo);
  var groupLambda = Expression.Lambda(propertyAccess, groupParameterExpression);
  var groupExpression = Expression.Call(typeof(Queryable), "GroupBy", new Type[] { collectionType, propInfo.PropertyType }, queryable.Expression, groupLambda);
  </code></pre>
  
  <p>I get a valid expression in <code>groupExpression</code> and the <code>type</code> received in this case when calling a <code>Name</code> property from a model is:</p>
  
  <p><code>IGrouping&lt;string, Product&gt;</code> where a Product is a model that looks like this:</p>
  
  <pre><code>public class Product
  {
      public string Name { get; set; }
  }
  </code></pre>
  
  <p><code>selectParameterExpression</code> is a parameter expression with a type of <code>IGrouping&lt;string,Product&gt;</code> .</p>
  
  <p>I get an exception when i try to call <code>FirstOrDefault</code> here:</p>
  
  <pre><code>var selectFirstOrDefaultMethodExpression = Expression.Call(typeof(Enumerable), "FirstOrDefault", new Type[] { collectionType }, selectParameterExpression);
  </code></pre>
  
  <blockquote>
    <p>No generic method 'FirstOrDefault' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.</p>
  </blockquote>