I have a VB.NET application and want to do Group By on multiple columns.
Class Structure:
Public Class Person
Public Property Name as String
Public Property City as String
Public Property Country as String
End Class
Dim oResult = PersonList _
.GroupBy(Function(v) New With {v.City, v.Country}) _
.Where(Function(grp) grp.Count > 1).ToList()
I have multiple person records which contains same city name & country name. But above query returns me zero items. if I am using only one column City or Country then it's working fine.
Dim oResult = PersonList _
.GroupBy(Function(v) v.City) _
.Where(Function(grp) grp.Count > 1).ToList()
Anyone point me where I am wrong with Group By LINQ query with multiple parameters.
The problem is that only Key
properties in anonymous types are used in equality and hashing in VB. (All properties in C# anonymous types are effectively key properties.) So you just need to change your query to:
Dim oResult = PersonList _
.GroupBy(Function(v) New With { Key v.City, Key v.Country}) _
.Where(Function(grp) grp.Count > 1).ToList()
See the documentation for anonymous types in VB for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With