Using System.Dynamic.Linq I have a group by statement that looks like this:
var rowGrouped = data.GroupBy(rGroup, string.Format("new({0})", c));
Where c
is just a string array of field names I need to have selected in my grouping. GroupBy
in this case returns a IEnumerable
(note: not an IEnumerable<T>
because we don't know what T
is). The regular GroupBy would return a System.Collections.Generic.IEnumerable<IGrouping<TKey, TElement>>
Now my question is, how do I iterate through the groups such that I have access to the key (Key
is defined in IGrouping<TKey, TElement>
but I don't know TKey
and TElement
a priori)?
I initially tried this:
foreach (var row in rowGrouped)
Which iterates, but I can't access row.Key
(row
in this case is type object
)
So I did this:
foreach (IGrouping<object,dynamic> row in rowGrouped)
Which, surprisingly, worked...as long as the key was a string. If, however, the key happened to be numeric (for example short
), then I get this error:
Unable to cast object of type 'Grouping`2[System.Int16,DynamicClass2]' to type
'System.Linq.IGrouping`2[System.Object,System.Object]'.
I need to be able to iterate through rowGrouped
and get the Key
for every row
and then iterate through the collection in each group.