Using System.Dynamic.Linq I have a group 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 that I need to select in my group. GroupBy in this case returns a IEnumerable (note: not a IEnumerable<T> , because we do not know what T ). A regular GroupBy would return System.Collections.Generic.IEnumerable<IGrouping<TKey, TElement>>
Now I ask the question, how can I iterate over groups so that I have access to the key ( Key is defined in IGrouping<TKey, TElement> , but I do not know TKey and TElement priori)?
I originally tried this:
foreach (var row in rowGrouped)
Iterate, but I cannot access row.Key ( row in this case is an object type)
So, I did this:
foreach (IGrouping<object,dynamic> row in rowGrouped)
Which, surprisingly, worked ... while the key was a string. If, however, the key is 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 iterate through rowGrouped and get the Key for each row , and then iterate over the collection in each group.