title: Access key after grouping by with dynamic linq
body: <p>Using <a href="https://github.com/kahanu/System.Linq.Dynamic" rel="noreferrer">System.Dynamic.Linq</a> I have a group by statement that looks like this:</p>
  
  <pre><code>var rowGrouped = data.GroupBy(rGroup, string.Format("new({0})", c));
  </code></pre>
  
  <p>Where <code>c</code> is just a string array of field names I need to have selected in my grouping. <code>GroupBy</code> in this case returns a <code>IEnumerable</code> (note: not an <code>IEnumerable&lt;T&gt;</code> because we don't know what <code>T</code> is). The regular <a href="http://msdn.microsoft.com/en-us/library/bb534304(v=vs.100).aspx" rel="noreferrer">GroupBy</a> would return a <code>System.Collections.Generic.IEnumerable&lt;IGrouping&lt;TKey, TElement&gt;&gt;</code></p>
  
  <p>Now my question is, how do I iterate through the groups such that I have access to the key (<code>Key</code> is defined in <code>IGrouping&lt;TKey, TElement&gt;</code> but I don't know <code>TKey</code> and <code>TElement</code> <em>a priori</em>)?</p>
  
  <p>I initially tried this:</p>
  
  <pre><code>foreach (var row in rowGrouped)
  </code></pre>
  
  <p>Which iterates, but I can't access <code>row.Key</code> (<code>row</code> in this case is type <code>object</code>)</p>
  
  <p>So I did this:</p>
  
  <pre><code>foreach (IGrouping&lt;object,dynamic&gt; row in rowGrouped)
  </code></pre>
  
  <p>Which, surprisingly, worked...as long as the key was a string. If, however, the key happened to be numeric (for example <code>short</code>), then I get this error:</p>
  
  <pre><code>Unable to cast object of type 'Grouping`2[System.Int16,DynamicClass2]' to type 
  'System.Linq.IGrouping`2[System.Object,System.Object]'.
  </code></pre>
  
  <p>I need to be able to iterate through <code>rowGrouped</code> and get the <code>Key</code> for every <code>row</code> and then iterate through the collection in each group.</p>