【发布时间】:2014-09-25 00:38:08
【问题描述】:
使用 System.Dynamic.Linq 我有一个如下所示的 group by 语句:
var rowGrouped = data.GroupBy(rGroup, string.Format("new({0})", c));
c 只是我需要在分组中选择的字段名称的字符串数组。 GroupBy 在这种情况下返回 IEnumerable(注意:不是 IEnumerable<T>,因为我们不知道 T 是什么)。常规的GroupBy 会返回一个System.Collections.Generic.IEnumerable<IGrouping<TKey, TElement>>
现在我的问题是,我如何遍历组以便我可以访问密钥(Key 在 IGrouping<TKey, TElement> 中定义,但我不知道 TKey 和 TElement a先验)?
我最初尝试过这个:
foreach (var row in rowGrouped)
其中迭代,但我无法访问row.Key(在这种情况下row 是类型object)
所以我这样做了:
foreach (IGrouping<object,dynamic> row in rowGrouped)
令人惊讶的是,只要键是字符串,它就可以工作。但是,如果密钥恰好是数字(例如 short),那么我会收到以下错误:
Unable to cast object of type 'Grouping`2[System.Int16,DynamicClass2]' to type
'System.Linq.IGrouping`2[System.Object,System.Object]'.
我需要能够遍历rowGrouped 并为每个row 获取Key,然后遍历每个组中的集合。
【问题讨论】:
-
我认为你不能只称它为
IGrouping<dynamic, dynamic>? -
@Chris:我也试过了。没用。同样的问题。