为什么一群匿名对象的关键不期望的行为方式?对象、行为、关键、方式

2023-09-04 06:50:16 作者:伤痛换来成长

我有这个formart的csv文件

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 _
                                                 } _
                                        )

我预计groupedResults数到4,而不是5,显示。 基本上,它没有按第1和第5排为一组。

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 ?

推荐答案

请匿名类型属性不变 - 这是方式来获得平等和散列工作。 (在C#中所有的匿名类型都是不可变的默认。)

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.)

试试这个

 Dim enumerable = _dt.AsEnumerable

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

编辑:部分意味着房地产是一个关键的匿名类型。请参阅 VB匿名类型的MSDN页面了解更多信息。

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