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.
The problem is that your key is a short
and you're trying to cast to an interface where the key is object
. While IGrouping<>
has covariant type parameters, it just simply won't work because variance only applies to reference types. Since short
is a value type, it will not work.
If you know the key will always be a short
, you should cast it as such.
foreach (IGrouping<short, dynamic> row in rowGrouped)
...
Otherwise if it's possible that it can be a value type or a reference type, it might just be easier to keep the entire row as dynamic
.
foreach (dynamic row in rowGrouped)
...
Though I personally have had troubles with this. Perhaps a bug but the runtime cannot figure out that the row has a Key
property in this case. I can't tell you why exactly but keep that in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With