为什么一群匿名对象的关键不期望的行为方式? [英] Why group by key of anonymous objects does not behave the way expected?

查看:100
本文介绍了为什么一群匿名对象的关键不期望的行为方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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.

这篇关于为什么一群匿名对象的关键不期望的行为方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆