title: Dynamic Linq Group By
body: <p>I am currently building reports and have a need to Group columns dynamically, depending on user's choice. Now, assuming that the situation is fixed on all columns, the query would be as follows:</p>
  
  <pre><code>var groupedInvoiceItems = invoiceItems.GroupBy(x =&gt; new { x.SalesInvoice.name, x.SalesInvoice.currencyISO, x.CatalogProduct });
  </code></pre>
  
  <p>Doing so would return results as desired, IGrouping. I would then run a loop to process the necessary data as below:</p>
  
  <pre><code>foreach (var groupedInvoiceItem in groupedInvoiceItems)
  {
      // Perform work here
  }
  </code></pre>
  
  <p>Now, the headache comes in when I try to make the Grouping dynamic by using Dynamic Linq. The query is as follows:</p>
  
  <pre><code>var groupedInvoiceItems = invoiceItems.GroupBy("new (SalesInvoice.name, SalesInvoice.currencyISO, CatalogProduct)", "it");
  </code></pre>
  
  <p>The problem with this is that it does not return IGrouping anymore. Hence, my foreach loop no longer works. Is there any solution to the matter? I tried casting IGrouping to the Dynamic query but to no avail. Help is needed urgently.</p>