views:

428

answers:

1

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 ?

+4  A: 

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.

Jon Skeet
Yup, checked the hashcodes they were different.
Biswanath
What does Key means ?
Biswanath
Yeah, Its working.
Biswanath
If we do not define key then how the hashcode or equality is evaluated ?
Biswanath
From the linked document: "An instance of an anonymous types that has no key properties is equal only to itself."
Jon Skeet