title: Linq - Dynamic GroupBy with IEnumerable<T>
body: <p>I have a collection that is <code>IEnumerable&lt;Transaction&gt;</code>.  Transaction has several properties such as TransactionId (Int64), PaymentMethod(string) and TransactionDate(DateTime)</p>
  
  <p>I'd like to be able to accomplish this <code>transactions.GroupBy(x =&gt; x.PaymentMethod)</code> dynamically at run time based on whatever grouping field the user has decided to use.</p>
  
  <p>I found most of the answer I'm looking for in dtb's answer here <a href="https://stackoverflow.com/questions/2914656/linq-groupby-how-to-specify-the-grouping-key-at-runtime">Linq GroupBy - how to specify the grouping key at runtime?</a></p>
  
  <p>This works well:</p>
  
  <pre><code>        var arg = Expression.Parameter( typeof( Transaction ), "transaction" );
          var body = Expression.Property( arg, "PaymentMethod" );
          var lambda = Expression.Lambda&lt;Func&lt;Transaction, string&gt;&gt;( body, arg );
          var keySelector = lambda.Compile();
  
          var groups = transactions.GroupBy( keySelector );
  </code></pre>
  
  <p>Except that I don't know the type of the return type of the Func in <code>Expression.Lambda&lt;Func&lt;Transaction, string&gt;&gt;</code>.  It's string in this example, but it might be Int64, decimal, DateTime, etc.  I can't use Object as the return type because I might have value types.</p>
  
  <p>I've been reading lots of SO posts and most of them seem to apply to IQueryable and LinqToSQL.  </p>
  
  <p>Using the Expression class seems like a good way to accomplish this, but is there a way to do it when I don't know either the name or datatype of my group parameter at compile time?</p>
  
  <p>I appreciate any nudge in the right direction.</p>
  
  <p>Edit:</p>
  
  <p>Using Polity's solution below, I created an extension method that does what I've been trying to do:</p>
  
  <pre><code>    public static IEnumerable&lt;IGrouping&lt;object, T&gt;&gt; GroupBy&lt;T&gt;( this IEnumerable&lt;T&gt; items, string groupByProperty )
      {
  
          var arg = Expression.Parameter( typeof(T), "item" );
          var body = Expression.Convert( Expression.Property( arg, groupByProperty ), typeof( object ) );
          var lambda = Expression.Lambda&lt;Func&lt;T, object&gt;&gt;( body, arg );
          var keySelector = lambda.Compile();
  
          var groups = items.GroupBy( keySelector );
          return groups;
      } 
  </code></pre>
  
  <p>Thanks to Polity and everyone who answered!</p>