LINQ Group By with multiple parameters

27,249

Solution 1

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.

Solution 2

Dim q1 = (From p In Repository.Table
                            Group p By p.CreatedDate.Year, p.CreatedDate.Month Into Group
                            Select New With {.Year = Year, .Month = Month, .Count = Group.Count()}).ToList

Or

Dim q2 = (From p In Repository.Table
                            Group p By key = New With {.Year = p.CreatedDate.Year, .Month = p.CreatedDate.Month} Into Group
                            Select New With {.Year = key.Year, .Month = key.Month, .Count = Group.Count()}).ToList
Share:
27,249

Related videos on Youtube

Jignesh Thakker
Author by

Jignesh Thakker

Updated on July 09, 2022

Comments

  • Jignesh Thakker
    Jignesh Thakker almost 2 years

    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.

  • Jignesh Thakker
    Jignesh Thakker about 11 years
    Thanks! It Works like a charm.
  • rahularyansharma
    rahularyansharma about 3 years
    What if we want to group by first character of city name ? and include all which have only one single item in group ?
  • Jon Skeet
    Jon Skeet about 3 years
    @rahularyansharma: I suggest you try that for yourself, using the answers here and other research, then ask a new question showing how far you've got and where you're stuck.

Related