Why group by key of anonymous objects does not behave the way expected?

て烟熏妆下的殇ゞ 提交于 2019-12-08 12:03:28

问题


I have a csv file of this formart

 A,B,value
 a1,b1,10
 a2,b1,12
 a2,b1,15
 a2,b2,14
 a1,b1,12

which I am converting as datatable in my application.

 Dim enumerable = _dt.AsEnumerable

 Dim groupedResults = enumerable.GroupBy( _
                                   Function(x) _
                                        New With { _
                                                  .A = x.Item("A").ToString, _
                                                  .B = x.Item("B").ToString _
                                                 } _
                                        )

I expected the groupedResults count to 4 instead of the 5 which shows.
Basically it does not group by 1st and 5 th row into one group.

I expected object with the same value will be produce same key.

What can be the reason for it ?


回答1:


Make the anonymous type properties immutable - that's the way to get equality and hashing to work. (In C# all anonymous types are immutable by default.)

Try this

 Dim enumerable = _dt.AsEnumerable

 Dim groupedResults = enumerable.GroupBy( _
               Function(x) _
                    New With { _
                              Key .A = x.Item("A").ToString, _
                              Key .B = x.Item("B").ToString _
                             } _
                    )

EDIT: The Key part means that property is a key for the anonymous type. See the VB anonymous types MSDN page for more details.



来源:https://stackoverflow.com/questions/626935/why-group-by-key-of-anonymous-objects-does-not-behave-the-way-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!