通过动态linq分组后的访问密钥 [英] Access key after grouping by with dynamic linq
问题描述
使用 System.Dynamic.Linq 我有一个类似的group by语句:
Using System.Dynamic.Linq I have a group by statement that looks like this:
var rowGrouped = data.GroupBy(rGroup, string.Format("new({0})", c));
c
只是字段名称的字符串数组,我需要在分组中选择它们.在这种情况下,GroupBy
返回IEnumerable
(注意:不是IEnumerable<T>
,因为我们不知道T
是什么).常规 GroupBy 将返回
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>>
现在我的问题是,如何遍历各个组,以便可以访问密钥(IGrouping<TKey, TElement>
在IGrouping<TKey, TElement>
中定义,但我不知道TKey
和TElement
a先验)?
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)?
我最初尝试过:
foreach (var row in rowGrouped)
进行迭代,但是我无法访问row.Key
(在这种情况下,row
是类型object
)
Which iterates, but I can't access row.Key
(row
in this case is type object
)
所以我做到了:
foreach (IGrouping<object,dynamic> row in rowGrouped)
令人惊讶的是,只要键是一个字符串,它就可以工作.但是,如果键碰巧是数字键(例如short
),则会出现此错误:
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]'.
我需要能够遍历rowGrouped
并为每个row
获取Key
,然后遍历每个组中的集合.
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.
推荐答案
问题是您的密钥是short
,并且您试图投射到密钥为object
的接口.尽管IGrouping<>
具有协变类型参数,但它只是行不通,因为仅变化适用于引用类型.由于short
是值类型,因此将不起作用.
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.
如果知道密钥将始终是short
,则应将其强制转换为这样.
If you know the key will always be a short
, you should cast it as such.
foreach (IGrouping<short, dynamic> row in rowGrouped)
...
否则,如果它可以是值类型或引用类型,则将整个行保留为dynamic
可能会更容易.
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)
...
尽管我个人对此有麻烦.在这种情况下,也许是一个错误,但是运行时无法确定该行具有Key
属性.我无法告诉您确切原因,但请记住这一点.
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.
这篇关于通过动态linq分组后的访问密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!