为什么按匿名对象的键分组不按预期方式运行?

时间:2021-05-20 01:46:02

I have a csv file of this formart

我有一个这个formart的csv文件

 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.

我期望分组结果计数为4而不是显示的5。基本上它不会将第1行和第5行分组为一组。

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

我期望具有相同值的对象将产生相同的键。

What can be the reason for it ?

可能是什么原因呢?

1 个解决方案

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

使匿名类型属性不可变 - 这是获得相等和散列的方法。 (在C#中,默认情况下所有匿名类型都是不可变的。)

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.

编辑:关键部分意味着属性是匿名类型的关键。有关更多详细信息,请参阅VB匿名类型MSDN页面。

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

使匿名类型属性不可变 - 这是获得相等和散列的方法。 (在C#中,默认情况下所有匿名类型都是不可变的。)

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.

编辑:关键部分意味着属性是匿名类型的关键。有关更多详细信息,请参阅VB匿名类型MSDN页面。